//
//  LSUtility.m
//  LearningSystemMEE
//
//  Created by heyong on 16/3/17.
//  Copyright © 2016年 bjttsx. All rights reserved.
//

/* *
 *iOS版本
 */
//#define DEF_IOS7         ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0 ? YES : NO)
//#define DEF_IOS7Dot0     ([[[UIDevice currentDevice] systemVersion] floatValue] == 7.0 ? YES : NO)
//#define DEF_IOS8         ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0 ? YES : NO)
// iOS10适配
#define DEF_IOS7         (NSFoundationVersionNumber >= NSFoundationVersionNumber_iOS_7_0 ? YES : NO)
#define DEF_IOS7Dot0     (NSFoundationVersionNumber == NSFoundationVersionNumber_iOS_7_0 ? YES : NO)
#define DEF_IOS8         (NSFoundationVersionNumber >= NSFoundationVersionNumber_iOS_8_0 ? YES : NO)

#import "LSUtility.h"
#import "MBProgressHUD.h"
#import "Reachability.h"
#import "SDWebImageManager.h"
@implementation LSUtility


//!!!!: 获取字符串字数
/**
 *  获取字符串字数   汉字算两个字 英文算一个字
 *
 *  @param text 传入字符串
 *
 *  @return 返回字符串位数
 */
+ (int)calculateTextLength:(NSString *)text
{
    float number = 0.0;
    for (int index = 0; index < [text length]; index++)
    {
        NSString *character = [text substringWithRange:NSMakeRange(index, 1)];
        if ([character lengthOfBytesUsingEncoding:NSUTF8StringEncoding] == 3)
        {
            number += 1;
        }
        else
        {
            number += 0.5f;
        }
    }
    return number;
}

//!!!!: 计算字符串的宽度和高度
/**
 *  计算字符串的宽度和高度
 *
 *  @param string 入参的字符串
 *  @param font
 *  @param cSize
 *
 *  @return
 */
//+ (CGSize)calculateStringSize:(NSString *)string font:(UIFont *)font constrainedSize:(CGSize)cSize
//{
//
//    if (DEF_IOS7)
//    {
//        NSDictionary *attribute = @{NSFontAttributeName: font};
//        CGRect rect = [string boundingRectWithSize:cSize options:NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:attribute context:nil];
//        return rect.size;
//    }
//    else
//    {
//        CGSize size = [string sizeWithFont:font constrainedToSize:cSize lineBreakMode:NSLineBreakByWordWrapping];
//        return size;
//    }
//    return CGSizeZero;
//}

/**
 *  动态算出文本大小
 *
 *  @param size   限制宽高
 *  @param font   字体的大小
 *  @param spacing 行间距
 *  @param string 内容
 *
 *  @return cgsize
 */
+(CGSize)boundingRectWithSize:(CGSize)size font:(UIFont*)font string:(NSString*)string withSpacing:(CGFloat)spacing
{
    NSMutableParagraphStyle * paragraphSpaceStyle = [[NSMutableParagraphStyle alloc] init];
    [paragraphSpaceStyle setLineSpacing:spacing];
    NSDictionary *attribute = @{NSFontAttributeName:font,NSParagraphStyleAttributeName:paragraphSpaceStyle};
    
    CGSize fitSize = [string boundingRectWithSize:size
                                          options:
                      NSStringDrawingTruncatesLastVisibleLine |
                      NSStringDrawingUsesLineFragmentOrigin |
                      NSStringDrawingUsesFontLeading
                                       attributes:attribute
                                          context:nil].size;
    
    return fitSize;
}

/**
 *  设置文字行间距
 *
 *  @param string   字符串
 *  @param font     字体大小
 *  @param spacing  间距大小
 *
 *  @return NSAttributedString
 */
+(NSAttributedString *)setLineSpacingWithString:(NSString *)string withFont:(CGFloat)font spacing:(CGFloat)spacing{
    
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:string];
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    [paragraphStyle setLineSpacing:spacing];//调整行间距
    [attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [string length])];
    [attributedString addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:font] range:NSMakeRange(0, [string length])];
    
    return attributedString;
}
//!!!!: 隐藏电话号码
/**
 *	@brief	隐藏电话号码
 *
 *	@param 	pNum 	电话号码
 *
 *	@return 186****1325
 */

+ (NSString *)securePhoneNumber:(NSString *)pNum
{
    if (pNum.length != 11)
    {
        return pNum;
    }
    NSString *result = [NSString stringWithFormat:@"%@****%@",[pNum substringToIndex:3],[pNum substringFromIndex:7]];
    return result;
}

//!!!!: 隐藏身份证号码
/**
 *	@brief	隐藏身份证号码
 *
 *	@param 	IdNum 	身份证号码
 *
 *	@return **************1325
 */
+ (NSString *)secureIdCard:(NSString *)IdNum
{
    NSString *result = @"";
    for (int i=0; i < IdNum.length - 4; i ++) {
        result = [NSString stringWithFormat:@"%@*",result];
    }
    result = [NSString stringWithFormat:@"%@%@",result,[IdNum substringFromIndex:IdNum.length - 4]];
    return result;
}
//!!!!: 显示toast提示框 time秒后自动消失
/**
 *	@brief	显示toast提示框 time秒后自动消失
 *
 *	@param 	message 	提示信息
 *
 *	@return
 */
+ (void)showToastWithMessage:(NSString *)message inView:(UIView *)view Andtime:(CGFloat)time
{
    MBProgressHUD *progressHUD = [[MBProgressHUD alloc] initWithView:view];
    [view addSubview:progressHUD];
    progressHUD.detailsLabelText = message;
    progressHUD.mode = MBProgressHUDModeText;
    
    //指定距离中心点的X轴和Y轴的偏移量，如果不指定则在屏幕中间显示
    progressHUD.yOffset = -100.0f;
    //    HUD.xOffset = 100.0f;
    
    [progressHUD showAnimated:YES whileExecutingBlock:^{
        sleep(time);
    } completionBlock:^{
        [progressHUD removeFromSuperview];
    }];
}

//!!!!: 系统提示框
/**
 *	@brief	系统提示框
 *
 *	@param 	message 	提示信息
 *
 *	@return
 */
+ (void)showAlertWithMessage:(NSString *)messages ok:(void (^)())ok cancel:(void (^)())cancel{
    UIAlertController *alertController=[UIAlertController alertControllerWithTitle:@"提示" message:messages preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        cancel();

    }];
    UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        ok();
    }];
    [alertController addAction:cancelAction];
    [alertController addAction:okAction];

    [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:alertController animated:YES completion:nil];
    //    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:message delegate:delegate cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
    //    [alert performSelectorOnMainThread:@selector(show) withObject:nil waitUntilDone:YES];
    
}

//!!!!: 风火轮加载信息
/**
 *  风火轮加载信息
 *
 *  @param _targetView 对象
 *  @param _msg        提示信息
 */
+ (void)showMBProgress:(UIView *)_targetView message:(NSString *)_msg
{
    
    MBProgressHUD *progressHUD = [[MBProgressHUD alloc] initWithView:_targetView];
    progressHUD.mode = MBProgressHUDModeIndeterminate;
    [progressHUD show:YES];
    progressHUD.labelText = _msg;
    [_targetView addSubview:progressHUD];
    
}
//!!!!:隐藏HUD

+ (void)hideMBProgress:(UIView*)_targetView
{
    [MBProgressHUD hideAllHUDsForView:_targetView animated:YES];
    //    [MBProgressHUD hideHUDForView:_targetView animated:YES];
}

+ (void)hideMBProgressNOAnimation:(UIView*)_targetView;
{
    [MBProgressHUD hideAllHUDsForView:_targetView animated:NO];
    
}

//判断是否是14位数字
+ (BOOL)isPureInt:(NSString*)string{
    if(string.length!=14){
        return NO;
    }else{
        NSScanner* scan = [NSScanner scannerWithString:string];
        int val;
        return[scan scanInt:&val] && [scan isAtEnd];
    }
}


//判断是否输入了emoji 表情
+ (BOOL)stringContainsEmoji:(NSString *)string
{
    __block BOOL returnValue = NO;
    NSLog(@"%@",string);
    [string enumerateSubstringsInRange:NSMakeRange(0, [string length])
                               options:NSStringEnumerationByComposedCharacterSequences
                            usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
                                const unichar hs = [substring characterAtIndex:0];
                                if (0xd800 <= hs && hs <= 0xdbff) {
                                    if (substring.length > 1) {
                                        const unichar ls = [substring characterAtIndex:1];
                                        const int uc = ((hs - 0xd800) * 0x400) + (ls - 0xdc00) + 0x10000;
                                        if (0x1d000 <= uc && uc <= 0x1f77f) {
                                            returnValue = YES;
                                        }
                                    }
                                } else if (substring.length > 1) {
                                    const unichar ls = [substring characterAtIndex:1];
                                    if (ls == 0x20e3) {
                                        returnValue = YES;
                                    }
                                } else {
                                    if (0x2100 <= hs && hs <= 0x27ff) {
                                        returnValue = YES;
                                    } else if (0x2B05 <= hs && hs <= 0x2b07) {
                                        returnValue = YES;
                                    } else if (0x2934 <= hs && hs <= 0x2935) {
                                        returnValue = YES;
                                    } else if (0x3297 <= hs && hs <= 0x3299) {
                                        returnValue = YES;
                                    } else if (hs == 0xa9 || hs == 0xae || hs == 0x303d || hs == 0x3030 || hs == 0x2b55 || hs == 0x2b1c || hs == 0x2b1b || hs == 0x2b50) {
                                        returnValue = YES;
                                    }
                                }
                            }];
    return returnValue;
}


//!!!!: 获取当前版本
/**
 *  获取当前版本
 *
 *  @return
 */
+ (NSString *)getLocalAppVersion
{
    NSString *path = [[NSBundle mainBundle] pathForResource:@"Info" ofType:@"plist"];
    NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:path];
    NSString *version = [dict objectForKey:@"CFBundleVersion"];
    return version;
}

//!!!!: 判断网络
/**
 *  判断网络
 *
 *  @return
 */
+ (BOOL)isConnectionAvailable
{
    BOOL isExistenceNetwork = YES;
    Reachability *reach = [Reachability reachabilityWithHostName:@"www.baidu.com"];
    switch ([reach currentReachabilityStatus])
    {
            //没有网
        case NotReachable:
            isExistenceNetwork = NO;
            break;
            //wifi
        case ReachableViaWiFi:
            isExistenceNetwork = YES;
            break;
            //2g 3g
        case ReachableViaWWAN:
            isExistenceNetwork = YES;
            break;
            
        default:
            break;
    }
    
    return isExistenceNetwork;
}
#pragma  tableview
//!!!!: 去掉横线
/**
 *  去掉多余横线
 *
 *  @return
 */
+ (void)setExtraCellLineHidde:(UITableView *)tableView tabHeader:(BOOL) header tabFooter:(BOOL) footer
{
    UIView *view =[ [UIView alloc]init];
    view.backgroundColor = [UIColor clearColor];
    if (!header) {
        [tableView setTableHeaderView:view];
    }
    if (!footer) {
        [tableView setTableFooterView:view];
    }
}

/**
 *  设置UILable里的文字两边对齐
 *  maxInteger    : 应占字符数 （中文为1，英文为0.5/个）
 *  currentString : 要显示的文字
 */
+(void)conversionCharacterInterval:(NSInteger)maxInteger current:(NSString *)currentString withLabel:(UILabel *)label
{
    CGRect rect = [[currentString substringToIndex:1] boundingRectWithSize:CGSizeMake(200,label.frame.size.height)
                                                                   options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading
                                                                attributes:@{NSFontAttributeName: label.font}
                                                                   context:nil];
    
    
    NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc] initWithString:currentString];
    float strLength = [LSUtility getLengthOfString:currentString];
    [attrString addAttribute:NSKernAttributeName value:@(((maxInteger - strLength) * rect.size.width)/(strLength - 1)) range:NSMakeRange(0, strLength)];
    label.attributedText = attrString;
}
+  (float)getLengthOfString:(NSString*)str {
    
    float strLength = 0;
    char *p = (char *)[str cStringUsingEncoding:NSUnicodeStringEncoding];
    for (NSInteger i = 0 ; i < [str lengthOfBytesUsingEncoding:NSUnicodeStringEncoding]; i++) {
        if (*p) {
            strLength++;
        }
        p++;
    }
    return strLength/2;
}



//!!!!: 计算单个文件大小
/**
 *	计算单个文件大小
 *
 *	@param 	path 	路径
 *
 *	@return float
 */
+(float)fileSizeAtPath:(NSString *)path{
    NSFileManager *fileManager=[NSFileManager defaultManager];
    if([fileManager fileExistsAtPath:path]){
        long long size=[fileManager attributesOfItemAtPath:path error:nil].fileSize;
        return size/1024.0/1024.0;
    }
    return 0;
}

//!!!!: 计算目录的大小
/**
 *	计算目录的大小
 *
 *	@param 	path 	地址
 *
 *	@return float
 */
+ (float)folderSizeAtPath:(NSString *)path
{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    float folderSize=0.f;
    if ([fileManager fileExistsAtPath:path]) {
        NSArray *childerFiles=[fileManager subpathsAtPath:path];
        for (NSString *fileName in childerFiles) {
            NSString *absolutePaths = [path stringByAppendingPathComponent:fileName];
            // 计算单个文件大小
            folderSize += [self fileSizeAtPath:absolutePaths];
        }
        //SDWebImage框架自身计算缓存的实现
        folderSize+=[[SDImageCache sharedImageCache] getSize]/1024.0/1024.0;
        return folderSize;
    }
    return 0;
}
//!!!!: 清理缓存文件
/**
 *	清理缓存文件
 *
 *	@param 	path 	地址
 *
 *	@return
 */
+(void)clearCache:(NSString *)path{
    NSFileManager *fileManager=[NSFileManager defaultManager];
    if ([fileManager fileExistsAtPath:path]) {
        NSArray *childerFiles=[fileManager subpathsAtPath:path];
        for (NSString *fileName in childerFiles) {
            //如有需要，加入条件，过滤掉不想删除的文件
            NSString *absolutePath=[path stringByAppendingPathComponent:fileName];
            [fileManager removeItemAtPath:absolutePath error:nil];
        }
    }
    [[SDImageCache sharedImageCache] cleanDisk];
}

//缓存大小
+ (NSString *)CachesSize{
    // 清除缓存
    CGFloat size = [self folderSizeAtPath:NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject];
    NSString *message = size > 1 ? [NSString stringWithFormat:@"%.f M", size] : [NSString stringWithFormat:@"%.f K", size * 1024.0];
    return message;
}

//清除缓存
+ (void)cleanCaches{
    
    [self clearCache:NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject];
    [self clearCache:NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES).firstObject];
    [self clearCache:NSTemporaryDirectory()];
}

//清理缓存
-(void) clearCaches
{
    dispatch_async(
                   dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                       NSString *cachPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0];
                       NSArray *files = [[NSFileManager defaultManager] subpathsAtPath:cachPath];
                       for (NSString *p in files) {
                           NSError *error;
                           NSString *path = [cachPath stringByAppendingPathComponent:p];
                           if ([[NSFileManager defaultManager] fileExistsAtPath:path]) {
                               [[NSFileManager defaultManager] removeItemAtPath:path error:&error];
                           }
                       }
                   });
}

//当前时间
+ (NSString *)TimeNow{
    NSDate *senddate=[NSDate date];
    NSDateFormatter *dateformatter=[[NSDateFormatter alloc] init];
    [dateformatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString *locationString=[dateformatter stringFromDate:senddate];
    return locationString;
}

// 获取当前时间(新)
+ (NSString *)nowTime {
    NSDate *senddate=[NSDate date];
    NSDateFormatter *dateformatter=[[NSDateFormatter alloc] init];
    [dateformatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString *locationString=[dateformatter stringFromDate:senddate];
    return locationString;
}

//时间加5秒
+ (NSString *)nowTimeAdd1Sec{
    NSDate *dates = [NSDate date];
    NSTimeInterval interval = 5 ;
    NSDate *detea = [NSDate dateWithTimeInterval:interval sinceDate:dates];
    NSDateFormatter  *dateformatter=[[NSDateFormatter alloc] init];
    [dateformatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"BeiJing"];
    [dateformatter setTimeZone:timeZone];
    NSString *  locationString=[dateformatter stringFromDate:detea];
    return locationString;
}

//时间加5分钟
+ (NSString *)nowTimeAdd5Sec{
    NSDate *dates = [NSDate date];
    NSTimeInterval interval = 300 ;
    NSDate *detea = [NSDate dateWithTimeInterval:interval sinceDate:dates];
    NSDateFormatter  *dateformatter=[[NSDateFormatter alloc] init];
    [dateformatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"BeiJing"];
    [dateformatter setTimeZone:timeZone];
    NSString *  locationString=[dateformatter stringFromDate:detea];
    return locationString;
}
// 获取当前日期
+ (NSString *)dateNow {
    NSDate *senddate=[NSDate date];
    NSDateFormatter *dateformatter=[[NSDateFormatter alloc] init];
    [dateformatter setDateFormat:@"yyyy-MM-dd"];
    NSString *locationString=[dateformatter stringFromDate:senddate];
    return locationString;
}

//去除0
+(NSString *)deletaeZero:(NSString *)str{
    if([[str substringToIndex:1]isEqualToString:@"0"]){
        return [str substringFromIndex:1];
    }else{
        return str;
    }
}

//判断能否切换项目
+ (BOOL)projectChangingBySignIn {
    return YES;
    // 如果为领导直接可以切换 总监直接退
    if ([USERROLE isEqualToString:@"LEADER_01"]||[USERROLE isEqualToString:@"USER_01"]) {
        
    }
    
    FMDatabase *db=[FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    [db open];
    NSString *sql=[NSString stringWithFormat:@"select * from work_record where  pro_id='%@' and RECORD_USER='%@' and RECORD_TYPE in('RECORD_05','RECORD_06') order by create_time", PROID, USERID];
    FMResultSet *resule=[db executeQuery:sql];
    NSMutableArray *typeArr=[NSMutableArray array];
    while ([resule next]) {
        NSString *type=[resule stringForColumn:@"RECORD_TYPE"];
        [typeArr addObject:type];
    }
    [db close];
    
    if(typeArr.count>0){
        if([[typeArr lastObject]isEqualToString:@"RECORD_06"]){
            return YES;
        }else{
            return NO;
        }
    }else{
        return YES;
    }
}
//查询配置表
+(NSDictionary *)querySystemConfig:(NSString *)name{
    FMDatabase *db=[FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    [db open];
    NSString *sql=[NSString stringWithFormat:@"select * from SYSTEM_CONFIG where  confname='%@'",name];
    FMResultSet *resule=[db executeQuery:sql];
    NSDictionary *dic;
    while ([resule next]) {
        dic=[resule resultDictionary];
    }
    [db close];
    if(dic){
        return dic;
    }else{
        NSLog(@"配置文件为空");
        return nil;
    }
}

//判断时间段

+ (BOOL)date:(NSDate*)date isBetweenDate:(NSDate*)beginDate andDate:(NSDate*)endDate
{
    if ([date compare:beginDate] ==NSOrderedAscending)
        return NO;
    
    if ([date compare:endDate] ==NSOrderedDescending)
        return NO;
    
    return YES;
}


//图片添加点击事件
+(void)imageAddTap:(UIImageView *)imageView{
    UITapGestureRecognizer *tap=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(imageTap:)];
    imageView.userInteractionEnabled=YES;
    [imageView addGestureRecognizer:tap];
}

//图片点击放大
+ (void)imageTap:(UITapGestureRecognizer *)tap{
    [LSTarBrowser showImage:(UIImageView *)tap.view];
}

//获取当前时间戳
+ (NSString *)getCurrentDateString
{
    
    //    NSTimeZone *zone = [NSTimeZone systemTimeZone];
    //    NSTimeInterval delta = [zone secondsFromGMTForDate:[NSDate date]];
    //    NSString *string = [NSString stringWithFormat:@"%f",[[NSDate date] timeIntervalSince1970] + delta];
    //    NSString *dateString = [[string componentsSeparatedByString:@"."]objectAtIndex:0];
    //    return dateString;
    
    //获取当前时间 精确到毫秒
    NSDateFormatter *formatter=[[NSDateFormatter alloc]init];
    [formatter setDateFormat:@"yyyyMMddhhmmssSSS"];
    NSString *date =[formatter stringFromDate:[NSDate date]];
    return [date stringByAppendingString:@".png"];
}

//取数组前9个元素（图片
+(NSMutableArray *)imageNumNinePicture:(NSMutableArray *)array{
    if(array.count<=9){
        return  array;
    }else{
        NSMutableArray *tempArray=[NSMutableArray array];
        for (int i=0; i<8; i++) {
            [tempArray addObject:array[i]];
        }
        return array;
    }
}


// 保存图片到沙盒(临时，可自动删除)
+ (void)saveImage:(UIImage *)currentImage withName:(NSString *)imageName{
    //高保真压缩图片可可将图片压缩，但图片质量基本保持不变，第二个参数即图片高保真参数。
    NSData *imageData=UIImageJPEGRepresentation(currentImage, 0.1);
    
    //创建Image临时文件夹
    NSFileManager *fileManager = [[NSFileManager alloc] init];
    NSString *createPath = DEF_IMAGEFILE_PATH;
    //图片存放目录
    NSString *fullPath=[createPath stringByAppendingPathComponent:imageName];
    // 判断文件夹是否存在，如果不存在，则创建
    if (![[NSFileManager defaultManager] fileExistsAtPath:createPath]) {
        [fileManager createDirectoryAtPath:createPath withIntermediateDirectories:YES attributes:nil error:nil];
    } else {
        NSLog(@"FileDir is exists.");
    }
    
    //图片写入文件
    [imageData writeToFile:fullPath atomically:NO];
    
    NSNotification * notice = [NSNotification notificationWithName:@"indexView" object:nil userInfo:nil];
    [[NSNotificationCenter defaultCenter]postNotification:notice];
}

// 保存图片到沙盒(永久，不自动删除)
+ (void)saveImagePermanent:(UIImage *)currentImage withName:(NSString *)imageName{
    
    //高保真压缩图片可可将图片压缩，但图片质量基本保持不变，第二个参数即图片高保真参数。
    NSData *imageData=UIImageJPEGRepresentation(currentImage, 0.1);
    
    NSFileManager *fileManager = [[NSFileManager alloc] init];
    
    NSString *createPath =DEF_FILE_PATH;
    
    NSString *fullPath=[createPath stringByAppendingPathComponent:imageName];
    
    // 判断文件夹是否存在，如果不存在，则创建
    if (![[NSFileManager defaultManager] fileExistsAtPath:createPath]) {
        [fileManager createDirectoryAtPath:createPath withIntermediateDirectories:YES attributes:nil error:nil];
    } else {
        NSLog(@"FileDir is exists.");
    }
    
    //图片写入文件
    [imageData writeToFile:fullPath atomically:NO];
}

//设置图片缩略图
+ (UIImage *)thumbnailWithImage:(UIImage *)image size:(CGSize)asize

{
    
    UIImage *newimage;
    
    if (nil == image) {
        
        newimage = nil;
        
    }
    
    else{
        
        UIGraphicsBeginImageContext(asize);
        
        [image drawInRect:CGRectMake(0, 0, asize.width, asize.height)];
        
        newimage = UIGraphicsGetImageFromCurrentImageContext();
        
        UIGraphicsEndImageContext();
        
    }
    
    return newimage;
    
}


/*!
 
 * @brief 把格式化的JSON格式的字符串转换成字典
 
 * @param jsonString JSON格式的字符串
 
 * @return 返回字典
 
 */
+ (id)dictionaryWithJsonString:(NSString *)jsonString {
    if (jsonString == nil) {
        return nil;
    }
    
    NSMutableString *mutStr = [NSMutableString
                               stringWithString:jsonString];
    NSRange range = {0,mutStr.length};
    
    //单引号变双引号
    [mutStr replaceOccurrencesOfString:@"\'"
                            withString:@"\\\""
                               options:NSLiteralSearch range:range];
    //特殊符号转换
    //    [mutStr replaceOccurrencesOfString:@"\n" withString:@"\\n" options:NSCaseInsensitiveSearch range:NSMakeRange(0, [mutStr length])];
    //    [mutStr replaceOccurrencesOfString:@"\b" withString:@"\\b" options:NSCaseInsensitiveSearch range:NSMakeRange(0, [mutStr length])];
    //    [mutStr replaceOccurrencesOfString:@"\f" withString:@"\\f" options:NSCaseInsensitiveSearch range:NSMakeRange(0, [mutStr length])];
    //    [mutStr replaceOccurrencesOfString:@"\r" withString:@"\\r" options:NSCaseInsensitiveSearch range:NSMakeRange(0, [mutStr length])];
    //    [mutStr replaceOccurrencesOfString:@"\t" withString:@"\\t" options:NSCaseInsensitiveSearch range:NSMakeRange(0, [mutStr length])];
    
    NSData *jsonData = [mutStr dataUsingEncoding:NSUTF8StringEncoding];
    
    NSError *err;
    
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                        options:NSJSONReadingMutableContainers
                                                          error:&err];
    
    if(err) {
        NSLog(@"json解析失败：%@",err);
        
        return nil;
    }
    return dic;
}

+ (id)arrayWithJsonString:(NSString *)jsonString{
    
    NSData *nsData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSArray *patrolArr = [NSJSONSerialization JSONObjectWithData:nsData options:kNilOptions error:&err];
    if(err) {
        NSLog(@"json解析失败：%@",err);
        return nil;
    }
    return patrolArr;
}

//首页使用
+ (id)indexDictionaryWithJsonString:(NSString *)jsonString {
    if (jsonString == nil) {
        return nil;
    }
    
    NSMutableString *mutStr = [NSMutableString
                               stringWithString:jsonString];
    NSRange range = {0,mutStr.length};
    
    //单引号变双引号
    [mutStr replaceOccurrencesOfString:@"\'"
                            withString:@"\""
                               options:NSLiteralSearch range:range];
    
    NSData *jsonData = [mutStr dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                        options:NSJSONReadingMutableContainers
                                                          error:&err];
    if(err) {
        NSLog(@"json解析失败：%@",err);
        return nil;
    }
    return dic;
}


/*
 *  字典转JSON
 */

+ (NSString*)dictionaryToJson:(id )dic
{
    NSError *parseError = nil;
    
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&parseError];
    
    NSString *jsonString=[[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    
    //去掉换行 空格
    
    NSMutableString *mutStr = [NSMutableString
                               stringWithString:jsonString];
    
    //    NSRange range = {0,jsonString.length};
    //
    //    [mutStr replaceOccurrencesOfString:@" "
    //                            withString:@""
    //                               options:NSLiteralSearch range:range];
    
    NSRange range2 = {0,mutStr.length};
    
    [mutStr replaceOccurrencesOfString:@"\n"
                            withString:@""
                               options:NSLiteralSearch range:range2];
    
    return mutStr;
}

/*
 *  字典转JSON_2
 */
+ (NSString*)dictionaryToJson_2:(id )dic
{
    NSError *parseError = nil;
    
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&parseError];
    
    NSString *jsonString=[[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    
    //去掉换行 空格
    
    NSMutableString *mutStr = [NSMutableString
                               stringWithString:jsonString];
    
    NSRange range = {0,jsonString.length};
    
    [mutStr replaceOccurrencesOfString:@" "
                            withString:@""
                               options:NSLiteralSearch range:range];
    
    NSRange range2 = {0,mutStr.length};
    
    [mutStr replaceOccurrencesOfString:@"\n"
                            withString:@""
                               options:NSLiteralSearch range:range2];
    return mutStr;
}

/*
 *  字典转JSON_3
 */

+ (NSString*)dictionaryToJson_3:(id )dic
{
    NSError *parseError = nil;
    
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&parseError];
    
    NSString *jsonString=[[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    
    //去掉换行 空格
    
    NSMutableString *mutStr = [NSMutableString
                               stringWithString:jsonString];
    
    NSRange range = {0,jsonString.length};
    
    [mutStr replaceOccurrencesOfString:@" "
                            withString:@""
                               options:NSLiteralSearch range:range];
    
    NSRange range2 = {0,mutStr.length};
    
    [mutStr replaceOccurrencesOfString:@"\n"
                            withString:@""
                               options:NSLiteralSearch range:range2];
    
    NSRange range3 = {0,mutStr.length};
    
    [mutStr replaceOccurrencesOfString:@"\""
                            withString:@""
                               options:NSLiteralSearch range:range3];
    
    return mutStr;
}

/*
 *  字典转JSON_4
 */

+ (NSString*)dictionaryToJson_4:(id )dic
{
    NSError *parseError = nil;
    
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&parseError];
    
    NSString *jsonString=[[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    
    //去掉换行 空格
    
    NSMutableString *mutStr = [NSMutableString
                               stringWithString:jsonString];
    
    
    NSRange range2 = {0,mutStr.length};
    
    [mutStr replaceOccurrencesOfString:@"\n"
                            withString:@""
                               options:NSLiteralSearch range:range2];
    
    return mutStr;
}


/*
 *  附件ids
 */

+ (NSString*)dictionaryToJson_5:(id )dic
{
    NSError *parseError = nil;
    
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&parseError];
    
    NSString *jsonString=[[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    
    //去掉换行 空格
    
    NSMutableString *mutStr = [NSMutableString
                               stringWithString:jsonString];
    
    NSRange range = {0,jsonString.length};
    
    [mutStr replaceOccurrencesOfString:@" "
                            withString:@""
                               options:NSLiteralSearch range:range];
    
    NSRange range2 = {0,mutStr.length};
    
    [mutStr replaceOccurrencesOfString:@"\n"
                            withString:@""
                               options:NSLiteralSearch range:range2];
    
    NSRange range3 = {0,mutStr.length};
    
    [mutStr replaceOccurrencesOfString:@"\""
                            withString:@""
                               options:NSLiteralSearch range:range3];
    
    NSRange range4 = {0,mutStr.length};
    
    [mutStr replaceOccurrencesOfString:@"["
                            withString:@""
                               options:NSLiteralSearch range:range4];
    
    NSRange range5 = {0,mutStr.length};
    
    [mutStr replaceOccurrencesOfString:@"]"
                            withString:@""
                               options:NSLiteralSearch range:range5];
    
    return mutStr;
}



//【】() "" '的转换
+ (NSMutableString *)SymbolConversion:(NSString *)conditions{
    NSMutableString *mutStr = [NSMutableString
                               stringWithString:conditions];
    NSRange range = {0,conditions.length};
    [mutStr replaceOccurrencesOfString:@"\""
                            withString:@"\'"
                               options:NSLiteralSearch range:range];
    NSRange range2 = {0,conditions.length};
    [mutStr replaceOccurrencesOfString:@"["
                            withString:@"("
                               options:NSLiteralSearch range:range2];
    
    NSRange range3 = {0,conditions.length};
    [mutStr replaceOccurrencesOfString:@"]"
                            withString:@")"
                               options:NSLiteralSearch range:range3];
    return mutStr;
}


// 将字典或者数组转化为JSON串
+ (NSString *)toJSONData:(id)theData {
    NSString *jsonString = nil;
    NSError *error = nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:theData
                                                       options:0
                                                         error:&error];
    if ([jsonData length] != 0 && error == nil){
        jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    } else {
        NSLog(@"转JSON失败%@", error);
    }
    return jsonString;
}

// 将JSON串转化为字典或者数组
+ (id)toArrayOrNSMutableDictionary:(NSData *)jsonData {
    if(jsonData){
        NSError *error = nil;
        id jsonObject = [NSJSONSerialization JSONObjectWithData:jsonData
                                                        options:NSJSONReadingAllowFragments
                                                          error:&error];
        
        if (jsonObject != nil && error == nil){
            return jsonObject;
        }else{
            //        NSLog(@"解析错误%@", error);
            return nil;
        }
    }else{
        return nil;
    }
}


//返回图片大小
+ (NSString *)imageDataLenth:(UIImage *)image{
    NSData * imageData = UIImageJPEGRepresentation(image,0.3);
    NSUInteger size=imageData.length;
    return [NSString stringWithFormat:@"%li",(unsigned long)size];
}


//返回本地ip地址
+ (NSString *)getIPAddress {
    NSString *address = @"error";
    struct ifaddrs *interfaces = NULL;
    struct ifaddrs *temp_addr = NULL;
    int success = 0;
    // retrieve the current interfaces - returns 0 on success
    success = getifaddrs(&interfaces);
    if (success == 0) {
        // Loop through linked list of interfaces
        temp_addr = interfaces;
        while(temp_addr != NULL) {
            if(temp_addr->ifa_addr->sa_family == AF_INET) {
                // Check if interface is en0 which is the wifi connection on the iPhone
                if([[NSString stringWithUTF8String:temp_addr->ifa_name] isEqualToString:@"en0"]) {
                    // Get NSString from C String
                    address = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)];
                }
            }
            temp_addr = temp_addr->ifa_next;
        }
    }
    // Free memory
    freeifaddrs(interfaces);
    return address;
}

// 根据用户id查用户名 和登录名
+(NSDictionary *)getuserIdByUserName:(NSString *)userId{
    if(userId==nil){
        NSLog(@"userId为nil");
        userId=@"";
    }
    FMDatabase *db=[FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    DBHelper *dbhelp= [DBHelper help];
    NSArray *nameArr=[dbhelp DataBase:db selectKeyTypes:@{@"USER_NAME":@"text",@"REAL_NAME":@"text",@"SEX":@"text",@"UNIT":@"text"} fromTable:USER whereCondition:@{@"ID":userId}];
    if(nameArr.count==0){
        NSLog(@"未查询到用户");
    }
    return  [nameArr lastObject];
}

//根据登录名 查询真是姓名
+(NSDictionary *)getuserNameByRealName:(NSString *)userName{
    if(userName==nil){
        NSLog(@"userId为nil");
        userName=@"";
    }
    FMDatabase *db=[FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    DBHelper *dbhelp= [DBHelper help];
    NSArray *nameArr=[dbhelp DataBase:db selectKeyTypes:@{@"REAL_NAME":@"text",@"SEX":@"text",@"UNIT":@"text"} fromTable:USER whereCondition:@{@"USER_NAME":userName}];
    if(nameArr.count==0){
        NSLog(@"未查询到用户");
    }
    return  [nameArr lastObject];
}



//根据项目id 查询可否配置
+(NSString *)queryProjectExtendInfoForId:(NSString *)proId{
    FMDatabase *db=[FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    [db open];
    NSString *sql=[NSString stringWithFormat:@"SELECT extend_Info from project where id='%@'",proId];
    FMResultSet *resule=[db executeQuery:sql];
    NSString *extendInfo=@"";
    while ([resule next]) {
        extendInfo=[resule stringForColumn:@"extend_Info"];
    }
    [db close];
    return DEFISNUL(extendInfo);
}



//根据用户名 查询userID
+(NSMutableArray *)getuserNameByUserID:(NSMutableArray *)userNameArr{
    FMDatabase *db=[FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    DBHelper *dbhelp= [DBHelper help];
    NSMutableArray *arr=[NSMutableArray array];
    for (NSString *user in userNameArr) {
        NSArray *nameArr=[dbhelp DataBase:db selectKeyTypes:@{@"ID":@"text"} fromTable:USER whereCondition:@{@"REAL_NAME":user}];
        NSDictionary *dic=[nameArr firstObject];
        [arr addObject:dic[@"ID"]];
    }
    return arr;
}

// 根据项目ID查项目名
+ (NSDictionary *)getProjectNameByProjectId:(NSString *)projectId {
    if(!projectId){
        NSLog(@"项目id为nil");
        return nil;
    }
    FMDatabase *db = [FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    DBHelper *dbhelp = [DBHelper help];
    NSArray *nameArr = [dbhelp DataBase:db selectStr:@"PROJECT_NAME" selectKeyTypes:@{@"PROJECT_NAME": @"text"} fromTable:PROJECT whereCondition:@{@"ID": projectId}];
    return [nameArr lastObject];
}

// 根据位置ID查项目位置名
+ (NSDictionary *)getAddressNameByAddressId:(NSString *)AddressId {
    FMDatabase *db = [FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    DBHelper *dbhelp = [DBHelper help];
    NSArray *nameArr = [dbhelp DataBase:db selectStr:@"ADDRESS_NAME" selectKeyTypes:@{@"ADDRESS_NAME": @"text"} fromTable:ADDRESS whereCondition:@{@"ID": AddressId}];
    return [nameArr lastObject];
}

// 根据单位项目ID查单位名
+ (NSDictionary *)getUnitNameByUnitId:(NSString *)unitId {
    FMDatabase *db = [FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    DBHelper *dbhelp = [DBHelper help];
    NSArray *nameArr = [dbhelp DataBase:db selectStr:@"PRO_UNIT_NAME" selectKeyTypes:@{@"PRO_UNIT_NAME": @"text"} fromTable:PROJECT_UNIT whereCondition:@{@"ID": unitId}];
    if(nameArr){
        return [nameArr lastObject];
    }else{
        NSLog(@"查询到单位为空");
        return nil;
    }
}

// 根据单位ID查单位名
+ (NSDictionary *)getUnitNameByUnitIdPro:(NSString *)unitId{
    if(!unitId){
        return nil;
    }
    FMDatabase *db=[FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    DBHelper *dbhelp= [DBHelper help];
    NSArray *nameArr=[dbhelp DataBase:db selectKeyTypes:@{@"ORGNAME":@"text"} fromTable:UNIT whereCondition:@{@"ID":unitId}];
    return  [nameArr lastObject];
}

//根据记录id 查询工作记录类型
+ (NSDictionary *)getSiteTypeBySiteId:(NSString *)SiteId{
    FMDatabase *db=[FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    DBHelper *dbhelp= [DBHelper help];
    NSArray *typeArr=[dbhelp DataBase:db selectKeyTypes:@{@"RECORD_TYPE":@"text"} fromTable:WORK_RECORD whereCondition:@{@"ID":SiteId}];
    return [typeArr lastObject];
}

//查询该人员的所有关联项目
+(NSMutableArray *)queryProsByUserId:(NSString *)userId{
    NSMutableArray *arr=[NSMutableArray array];
    FMDatabase *db=[FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    DBHelper *dbhelp= [DBHelper help];
    
    NSArray *typeArr=[dbhelp DataBase:db selectKeyTypes:@{@"PRO_ID":@"text"} fromTable:PROJECT_USER whereCondition:@{@"USER_ID":userId}];
    
    for (NSDictionary *dic in typeArr) {
        [arr addObject:dic[@"PRO_ID"]];
    }
    return arr;
}

//根据用户名 项目名查询身份
+(NSString *)getIdentityByUserId:(NSString *)userid andProId:(NSString *)proid{
    FMDatabase *db=[FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    [db open];
    NSString *sql=[NSString stringWithFormat:@"SELECT USER_TYPE FROM PROJECT_USER WHERE PRO_ID='%@' and user_id='%@' order by USER_TYPE",proid,userid];
    FMResultSet *resule=[db executeQuery:sql];
    
    NSMutableArray *typeArr=[NSMutableArray array];
    while ([resule next]) {
        NSString *type=[resule stringForColumn:@"USER_TYPE"];
        [typeArr addObject:type];
    }
    [db close];
    return [typeArr firstObject];
}

//根据日记id查询身份 总监返回yes
+(BOOL)getDiaryType:(NSString *)diaryId{
    FMDatabase *db=[FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    [db open];
    NSString *sql=[NSString stringWithFormat:@"select diary_type from work_diary where id='%@'",diaryId];
    
    FMResultSet *resule=[db executeQuery:sql];
    
    BOOL isType=YES;
    while ([resule next]) {
        NSString *type=[resule stringForColumn:@"diary_type"];
        if([type isEqualToString:@"DIARY_02"]){
            isType=NO;
        }else{
            isType=YES;
        }
    }
    [db close];
    return isType;
}



//判断是否添加日记
+ (BOOL)isExistAndType{
    NSString *role=DEF_PERSISTENT_GET_OBJECT(@"role");
    NSString *type=@"";
    if([role isEqualToString:@"USER_01"]){
        type=@"DIARY_01";
    }
    if([role isEqualToString:@"USER_03"]||[role isEqualToString:@"USER_07"]){
        type=@"DIARY_02";
    }
    //判断是否已经添加
    NSString *sql=[NSString stringWithFormat:@"SELECT id,date(DIARY_TIME),date(CREATE_TIME) FROM WORK_DIARY WHERE  date(DIARY_TIME) = '%@' AND DIARY_USER='%@' and pro_id='%@' and diary_type='%@'",[LSUtility dateNow],USERID,PROID,type];
    FMDatabase *db=[FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    [db open];
    FMResultSet *result=[db executeQuery:sql];
    NSString *isTimeExist;
    while ([result next]) {
        isTimeExist=[result stringForColumn:@"date(DIARY_TIME)"];
    }
    [db close];
    if([isTimeExist isEqualToString:[LSUtility dateNow]]){
        return YES;
    }else
        return NO;
}



#pragma mark -- 地图

//中国城市
+ (NSMutableArray *)getCityIdByCityName:(NSString *)cityName{
    FMDatabase *db=[FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    [db open];
    NSString *sql=[NSString stringWithFormat:@"select *from wbs_city where city_short_name ='%@'",cityName];
    FMResultSet *resule=[db executeQuery:sql];
    
    NSMutableArray *typeArr=[NSMutableArray array];
    while ([resule next]) {
        NSString *cityId=[resule stringForColumn:@"ID"];
        NSString *cityType=[resule stringForColumn:@"city_type"];
        NSDictionary *dic=@{@"cityId":cityId,@"cityType":cityType};
        [typeArr addObject:dic];
    }
    [db close];
    return typeArr;
}

//根据国家名 返回 id
+(NSString *)getCountryIdByCountryName:(NSString *)countryName{
    FMDatabase *db=[FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    [db open];
    NSString *sql=[NSString stringWithFormat:@"SELECT * from area where name=' %@'",countryName];
    FMResultSet *resule=[db executeQuery:sql];
    NSString *countryId=@"";
    while ([resule next]) {
        countryId=[resule stringForColumn:@"ID"];
    }
    [db close];
    return DEFISNUL(countryId);
}

//根据国家名 返回国家中心经纬度
+(NSDictionary *)getCountrylongLatByCountryName :(NSString *)countryName{
    FMDatabase *db=[FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    [db open];
    NSString *sql=[NSString stringWithFormat:@"select * from AREA where name=' %@'",countryName];
    FMResultSet *resule=[db executeQuery:sql];
    NSMutableDictionary *dic=[NSMutableDictionary dictionary];
    while ([resule next]) {
        [dic setObject:[resule stringForColumn:@"LON"] forKey:@"longitude"];
        [dic setObject:[resule stringForColumn:@"LAT"] forKey:@"latitude"];
    }
    [db close];
    return dic;
}

#pragma mark -- 巡 检
//根据用户名 项目名查询 所有 身份
+ (NSMutableArray *)getIdentitysByUserId:(NSString *)userid andProId:(NSString *)proid andUserType:(NSString *)userType {
    FMDatabase *db=[FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    [db open];
    //查询项目人员表
    NSString *sql=[NSString stringWithFormat:@"SELECT DISTINCT(USER_TYPE),PRO_ID FROM PROJECT_USER WHERE PRO_ID = '%@' and user_id='%@' AND USER_TYPE != '%@' order by USER_TYPE", proid, userid, userType];
    FMResultSet *resule=[db executeQuery:sql];
    
    NSMutableArray *typeArr=[NSMutableArray array];
    while ([resule next]) {
        NSMutableDictionary *dic=[NSMutableDictionary dictionary];
        NSString *type=[resule stringForColumn:@"USER_TYPE"];
        NSString *proId=[resule stringForColumn:@"PRO_ID"];
        [dic setObject:type forKey:@"userType"];
        [dic setObject:proId forKey:@"proId"];
        [typeArr addObject:dic];
    }
    // 查询巡检组人员表
    NSString *sql_2=[NSString stringWithFormat:@"SELECT DISTINCT(IGU.INSPECT_USER_TYPE) as type,ip.PRO_ID AS proId FROM INSPECT_GROUP_USER IGU LEFT JOIN USER U ON IGU.INSPECT_USER_ID=U.ID LEFT JOIN inspect_group insg ON insg.id=IGU.inspect_group_id LEFT JOIN inspect_process ip ON ip.inspect_group_id=IGU.inspect_group_id where IGU.INSPECT_USER_ID='%@' and ip.PRO_ID='%@' AND INSPECT_USER_TYPE != '%@'", userid, proid, userType];
    FMResultSet *resule_2=[db executeQuery:sql_2];
    
    while ([resule_2 next]) {
        NSMutableDictionary *dic=[NSMutableDictionary dictionary];
        NSString *type=[resule_2 stringForColumn:@"type"];
        NSString *proId=[resule_2 stringForColumn:@"proId"];
        [dic setObject:type forKey:@"userType"];
        [dic setObject:proId forKey:@"proId"];
        [typeArr addObject:dic];
    }
    
    [db close];
    return typeArr;
}

//根据用户名 项目名 查询联表查询巡检角色表
+(NSArray *)getIdentitysByInspectUserId:(NSString *)userid andProId:(NSString *)proid{
    FMDatabase *db=[FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    [db open];
    NSString *sql=[NSString stringWithFormat:@"SELECT distinct(IGU.id) as aa,IGU.*,ip.PRO_ID AS proId FROM INSPECT_GROUP_USER IGU LEFT JOIN USER U ON IGU.INSPECT_USER_ID=U.ID LEFT JOIN inspect_group insg ON insg.id=IGU.inspect_group_id LEFT JOIN inspect_process ip ON ip.inspect_group_id=IGU.inspect_group_id where IGU.INSPECT_USER_ID='%@' and ip.PRO_ID='%@'",proid,userid];
    FMResultSet *resule=[db executeQuery:sql];
    
    NSMutableArray *typeArr=[NSMutableArray array];
    while ([resule next]) {
        NSString*type=[resule stringForColumn:@"INSPECT_USER_TYPE"];
        if([type isEqualToString:@"1"]){
            type=@"巡检组长";
        }else if ([type isEqualToString:@"2"]){
            type=@"巡检员";
        }
        [typeArr addObject:type];
    }
    [db close];
    return typeArr;
}

//根据流程id 查询流程类型(督办, 跟进, 验收)
+ (NSDictionary *)processTypeByprocessId:(NSString *)processId {
    
    FMDatabase *db=[FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    DBHelper *dbhelp= [DBHelper help];
    NSArray *typeArr = [dbhelp DataBase:db selectKeyTypes:@{@"PROCESS_TYPE":@"integer"} fromTable:PROCESS whereCondition:@{@"ID":processId}];
    return [typeArr lastObject];
}

+ (void)deleteTable:(NSString *)table andIdArr:(NSMutableArray *)idArr{
    FMDatabase *db=[FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    [db open];
    for (NSString *idStr in idArr) {
        
        NSString *sql=[NSString stringWithFormat:@"DELETE FROM %@ WHERE ID ='%@'",table,idStr];
        
        if([db executeUpdate:sql]){
            //            NSLog(@"删除成功");
        }
    }
    [db close];
}

//查询未同步数据 最后的修改时间
+ (NSMutableArray *)getIdAndModifyTimeFromTable:(NSString *)table {
    
    FMDatabase *db=[FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    [db open];
    NSString *sql=[NSString stringWithFormat:@"SELECT ID, MODIFY_TIME, LOCAL_MODIFY_STATE FROM %@ WHERE LOCAL_MODIFY_STATE NOT IN('ADD','MOD')",table];
    FMResultSet *resule=[db executeQuery:sql];
    
    NSMutableArray *idAndModifyTimeArr=[NSMutableArray array];
    while ([resule next]) {
        NSString *localType=[resule stringForColumn:@"LOCAL_MODIFY_STATE"];
        //要删除的数据
        if([localType isEqualToString:@"DEL"]){
            NSString *ids=[resule stringForColumn:@"ID"];
            NSString *modify=[resule stringForColumn:@"MODIFY_TIME"];
            NSDictionary *dic=@{@"id":ids,@"modifyTime":DEFISNUL(modify), @"syncState":@"-2"};
            [idAndModifyTimeArr addObject:dic];
        }else{
            NSString *ids=[resule stringForColumn:@"ID"];
            NSString *modify=[resule stringForColumn:@"MODIFY_TIME"];
            NSDictionary *dic=@{@"id":ids,@"modifyTime":DEFISNUL(modify)};
            [idAndModifyTimeArr addObject:dic];
        }
    }
    
    [db close];
    if(idAndModifyTimeArr.count>0){
        return idAndModifyTimeArr;
        
    } else {
        return nil;
    }
}

// 查询人员项目下项目人员数量
+ (NSMutableArray *)queryUserNumByProId:(NSString *)userId andType:(NSString *)type {
    
    FMDatabase *db=[FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    DBHelper *helper=[DBHelper help];
    //根据id查询到关联项目
    NSArray *proIdArr=[helper DataBase:db selectStr:@"distinct(PRO_ID)" selectKeyTypes:@{@"PRO_ID":@"text"} fromTable:PROJECT_USER whereCondition:@{@"USER_ID":userId}];
    [db close];
    
    NSMutableArray *idAndModifyTimeArr=[NSMutableArray array];
    
    //项目id 查询项目人员
    for (NSDictionary *dic in proIdArr) {
        NSString *proId=dic[@"PRO_ID"];
        [db open];
        NSString *sql=[NSString stringWithFormat:@"select count(1) as count,MODIFY_TIME from project_user where pro_id='%@'",proId];
        FMResultSet *resule=[db executeQuery:sql];
        while ([resule next]) {
            NSString *modify=[resule stringForColumn:@"MODIFY_TIME"];
            NSString *count=[resule stringForColumn:@"count"];
            NSDictionary *dic=@{@"proId":proId,type:count,@"modifyTime":DEFISNUL(modify)};
            [idAndModifyTimeArr addObject:dic];
        }
        [db close];
    }
    if(idAndModifyTimeArr.count > 0){
        return idAndModifyTimeArr;
    }
    else{
        return nil;
    }
}

//查询人员项目下项目人员数量
+(NSMutableArray *)queryUnitNumByProId:(NSString *)userId andType:(NSString *)type{
    FMDatabase *db=[FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    DBHelper *helper=[DBHelper help];
    //根据id查询到关联项目
    NSArray *proIdArr=[helper DataBase:db selectStr:@"distinct(PRO_ID)" selectKeyTypes:@{@"PRO_ID":@"text"} fromTable:PROJECT_USER whereCondition:@{@"USER_ID":userId}];
    [db close];
    
    NSMutableArray *idAndModifyTimeArr=[NSMutableArray array];
    
    //项目id 查询单位数量
    for (NSDictionary *dic in proIdArr) {
        NSString *proId=dic[@"PRO_ID"];
        [db open];
        NSString *sql=[NSString stringWithFormat:@"select count(1) as count,MODIFY_TIME from PROJECT_UNIT where pro_id='%@'",proId];
        FMResultSet *resule=[db executeQuery:sql];
        while ([resule next]) {
            NSString *modify=[resule stringForColumn:@"MODIFY_TIME"];
            NSString *count=[resule stringForColumn:@"count"];
            NSDictionary *dic=@{@"proId":proId,type:count,@"modifyTime":DEFISNUL(modify)};
            [idAndModifyTimeArr addObject:dic];
        }
        [db close];
    }
    if(idAndModifyTimeArr.count>0){
        return idAndModifyTimeArr;
    }
    else{
        return nil;
    }
}


//查询该项目下总人员
+ (NSMutableArray *)queryUserByPro:(NSString *)proId{
    NSMutableArray *userNameArr=[NSMutableArray array];
    FMDatabase *db=[FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    [db open];
    
    //总监or监理
    NSString *sql1=[NSString stringWithFormat:@"SELECT DISTINCT(u.id),u.real_name,pu.USER_TYPE FROM USER AS u ,PROJECT_USER AS pu where u.ID = pu.USER_ID  and pu.PRO_ID='%@' and pu.USER_TYPE like 'u%%' group by (u.id) order by pu.user_type",proId];
    FMResultSet *resule=[db executeQuery:sql1];
    while ([resule next]) {
        NSString *userId=[resule stringForColumn:@"ID"];
        NSString *name=[resule stringForColumn:@"REAL_NAME"];
        NSDictionary *dic=@{@"id":userId,@"name":name};
        [userNameArr addObject:dic];
    }
    //施工方
    NSString *sql2=[NSString stringWithFormat:@"SELECT DISTINCT(u.id),u.real_name,pu.USER_TYPE FROM USER AS u ,PROJECT_USER AS pu where u.ID = pu.USER_ID  and pu.PRO_ID='%@' and pu.USER_TYPE like 'c%%' group by (u.id) order by pu.user_type",proId];
    FMResultSet *resule2=[db executeQuery:sql2];
    while ([resule2 next]) {
        NSString *userId=[resule2 stringForColumn:@"ID"];
        NSString *name=[resule2 stringForColumn:@"REAL_NAME"];
        NSDictionary *dic=@{@"id":userId,@"name":name};
        [userNameArr addObject:dic];
    }
    //      [db open];
    [db close];
    return userNameArr;
}


/**
 *  记录是否为同一天  是否生成日记
 */
+ (BOOL)isSameDay:(NSString*)timeStr
{
    NSString *time=[timeStr substringToIndex:10];
    NSString *nowStr=[[LSUtility TimeNow] substringToIndex:10];
    //判断是否生成日记
    FMDatabase *db=[FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    [db open];
    NSString *sql=[NSString stringWithFormat:@"SELECT * FROM WORK_DIARY where PRO_ID='%@' and DIARY_USER='%@' AND CREATE_TIME LIKE '%@%%' ORDER BY CREATE_TIME DESC",PROID,USERID,nowStr];
    FMResultSet *result=[db executeQuery:sql];
    NSMutableArray *arr=[NSMutableArray array];
    while ([result next]) {
        [arr addObject:[result stringForColumn:@"ID"]];
    }
    [db close];
    //当天 并且未生成日记
    if(arr.count>0){
        return NO;
    }else{
        if(![time isEqualToString:nowStr]){
            return NO;
        }
    }
    return YES;
}


/**
 *  是否为同一天  是否生成日记
 */
+ (BOOL)isSameDay:(NSString*)timeStr andRecordId:(NSString *)recordId
{
    BOOL is=YES;
    NSString *role=DEF_PERSISTENT_GET_OBJECT(@"role");
    NSString *diaryType=@"";
    if([role isEqualToString:@"USER_01"]){
        role=@"0";
        diaryType=@"DIARY_01";
    }else if ([role isEqualToString:@"USER_03"]||[role isEqualToString:@"USER_07"]){
        role=@"1";
        diaryType=@"DIARY_02";
    }
    
    NSString *time=[timeStr substringToIndex:10];
    NSString *nowStr=[[LSUtility TimeNow] substringToIndex:10];
    //判断是否生成日记
    FMDatabase *db=[FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    [db open];
    NSString *sql=[NSString stringWithFormat:@"SELECT * FROM WORK_DIARY where PRO_ID='%@' and DIARY_USER='%@' and DIARY_TYPE='%@'AND CREATE_TIME LIKE '%@%%' ORDER BY CREATE_TIME DESC ",PROID,USERID,diaryType,nowStr];
    FMResultSet *result=[db executeQuery:sql];
    NSMutableArray *arr=[NSMutableArray array];
    while ([result next]) {
        [arr addObject:[result stringForColumn:@"ID"]];
    }
    //当天 并且未生成日记
    if(arr.count>0){
        is= NO;
    }else{
        if(![time isEqualToString:nowStr]){
            is= NO;
        }
    }
    
    BOOL isR=NO;
    
    //记录id是本人
    NSString *sqlR=[NSString stringWithFormat:@"SELECT id From work_record where id='%@' and state='%@'",recordId,role];
    FMResultSet *resultR=[db executeQuery:sqlR];
    while ([resultR next]) {
        isR=YES;
    }
    
    [db close];
    
    if(isR&&is){
        return YES;
    }else{
        return NO;
    }
    
}

/**
 *  是否为同一天 总监是否审阅
 */
+ (BOOL)isSameDayDiary:(NSString*)timeStr andTyepe:(NSString *)type
{
    NSString *time=[timeStr substringToIndex:10];
    NSString *nowStr=[[LSUtility TimeNow] substringToIndex:10];
    
    //当天 并且未生成日记 是否审阅
    if([type isEqual:@"1"]){
        return NO;
    }else{
        if(![time isEqualToString:nowStr]){
            return NO;
        }
    }
    return YES;
}


/**
 * 判断流程是否同步，同步后不能编辑，否则可以编辑。
 */
+(BOOL)queryProcessIsSync:(NSString *)processId{
    NSString *sqlStr=[NSString stringWithFormat:@"SELECT LOCAL_MODIFY_STATE FROM PROCESS where ID='%@' ",processId];
    
    FMDatabase *db=[FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    
    [db open];
    FMResultSet *resule=[db executeQuery:sqlStr];
    BOOL is=NO;
    
    while ([resule next]) {
        NSString *local=[resule stringForColumn:@"LOCAL_MODIFY_STATE"];
        if([local isEqualToString:@"ADD"]||[local isEqualToString:@"MOD"]){
            is=YES;
        }else{
            is=NO;
        }
    }
    [db close];
    return is;
}

/**
 * 判断流程记录表条数是否大于2
 */
+(BOOL)queryProcessRecordCount:(NSString *)processId{
    NSString *sqlStr=[NSString stringWithFormat:@"SELECT id FROM PROCESS_RECORD where PROCESS_ID='%@' ",processId];
    
    FMDatabase *db=[FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    
    [db open];
    FMResultSet *resule=[db executeQuery:sqlStr];
    BOOL is=NO;
    NSMutableArray *array=[NSMutableArray array];
    while ([resule next]) {
        NSString *ids=[resule stringForColumn:@"id"];
        [array addObject:ids];
    }
    if(array.count>=2){
        is=YES;
    }else{
        is=NO;
    }
    [db close];
    return is;
}


//计算指定时间和当前时间 时间差 单位H
+(NSString *)timeDifferenceByTime:(NSString *)time{
    // 截止时间字符串格式
    NSString *expireDateStr = time;
    
    NSDateFormatter *dateFomatter = [[NSDateFormatter alloc] init];
    dateFomatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
    NSDate *nowDate = [NSDate date];
    
    NSTimeZone *zone = [NSTimeZone systemTimeZone];
    NSInteger interval = [zone secondsFromGMTForDate: nowDate];
    NSDate *localeDate = [nowDate  dateByAddingTimeInterval: interval];
    
    // 当前时间字符串格式
    NSString *nowDateStr = [dateFomatter stringFromDate:localeDate];
    
    // 截止时间data格式
    NSDate *expireDate = [dateFomatter dateFromString:expireDateStr];
    
    NSInteger interval1 = [zone secondsFromGMTForDate: nowDate];
    expireDate = [expireDate  dateByAddingTimeInterval: interval1];
    
    // 当前时间data格式
    localeDate = [dateFomatter dateFromString:nowDateStr];
    // 当前日历
    NSCalendar *calendar = [NSCalendar currentCalendar];
    // 需要对比的时间数据
    NSCalendarUnit unit = NSCalendarUnitYear | NSCalendarUnitMonth
    | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
    
    //    NSLog(@"nowDate:%@--expireDate:%@",localeDate,expireDate);
    
    // 对比时间差
    NSDateComponents *dateCom = [calendar components:unit fromDate:localeDate toDate:expireDate options:0];
    
    //    NSLog(@"时差:%@",dateCom);
    
    long sumHours=(dateCom.day * 24)+(dateCom.hour);
    
    NSString *str=[NSString stringWithFormat:@"%li",sumHours];
    
    return str;
}



//计算指定时间和当前时间 时间差 单位H
+(long )timeDifferenceByTimeDel:(NSString *)time{
    // 截止时间字符串格式
    NSString *expireDateStr = time;
    
    NSDateFormatter *dateFomatter = [[NSDateFormatter alloc] init];
    dateFomatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
    NSDate *nowDate = [NSDate date];
    
    NSTimeZone *zone = [NSTimeZone systemTimeZone];
    NSInteger interval = [zone secondsFromGMTForDate: nowDate];
    NSDate *localeDate = [nowDate  dateByAddingTimeInterval: interval];
    
    // 当前时间字符串格式
    NSString *nowDateStr = [dateFomatter stringFromDate:localeDate];
    
    // 截止时间data格式
    NSDate *expireDate = [dateFomatter dateFromString:expireDateStr];
    
    NSInteger interval1 = [zone secondsFromGMTForDate: nowDate];
    expireDate = [expireDate  dateByAddingTimeInterval: interval1];
    
    // 当前时间data格式
    localeDate = [dateFomatter dateFromString:nowDateStr];
    // 当前日历
    NSCalendar *calendar = [NSCalendar currentCalendar];
    // 需要对比的时间数据
    NSCalendarUnit unit = NSCalendarUnitYear | NSCalendarUnitMonth
    | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
    
    
    // 对比时间差
    NSDateComponents *dateCom = [calendar components:unit fromDate:localeDate toDate:expireDate options:0];
    
    //    NSLog(@"时差:%@",dateCom);
    
    long sumHours=(dateCom.day * 24)+(dateCom.hour);
    
    return  sumHours;
}




///判断 当前日期 是否超过指定日期24：00
+(long )timeDifferenceDay:(NSString *)time{
    // 截止时间字符串格式
    NSString *expireDateStr = time;
    
    NSDateFormatter *dateFomatter = [[NSDateFormatter alloc] init];
    dateFomatter.dateFormat = @"yyyy-MM-dd";
    NSDate *nowDate = [NSDate date];
    
    NSTimeZone *zone = [NSTimeZone systemTimeZone];
    NSInteger interval = [zone secondsFromGMTForDate: nowDate];
    NSDate *localeDate = [nowDate  dateByAddingTimeInterval: interval];
    
    
    // 截止时间data格式
    NSDate *expireDate = [dateFomatter dateFromString:expireDateStr];
    
    NSInteger interval1 = [zone secondsFromGMTForDate: nowDate];
    expireDate = [expireDate  dateByAddingTimeInterval: interval1];
    
    // 当前时间data格式
//    localeDate = [dateFomatter dateFromString:localeDate];
    // 当前日历
    NSCalendar *calendar = [NSCalendar currentCalendar];
    // 需要对比的时间数据
    NSCalendarUnit unit = NSCalendarUnitYear | NSCalendarUnitMonth
    | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
    
    //    NSLog(@"nowDate:%@--expireDate:%@",localeDate,expireDate);
    
    // 对比时间差
    NSDateComponents *dateCom = [calendar components:unit fromDate:localeDate toDate:expireDate options:0];
    
    //    NSLog(@"时差:%@",dateCom);
    
    long sumHours=dateCom.day ;
    
    return  sumHours;
}


//删除过期的图片（一天以后过期）
+(void)deleteOutofdateImageFile{
    //判断附件是否超过一天
    NSFileManager *fileManager = [NSFileManager defaultManager];
    //获取本地Documents路径
    NSArray*fileList = [[NSArray alloc]init];
    //得到目录下文件名
    fileList=[fileManager contentsOfDirectoryAtPath:DEF_IMAGEFILE_PATH error:nil];
    //    NSLog(@"文件路径：%@",DEF_IMAGEFILE_PATH);
    for (NSString *fileName in fileList) {
        NSString *filePath=[DEF_IMAGEFILE_PATH stringByAppendingString:[NSString stringWithFormat:@"/%@",fileName]];
        NSDictionary *fileAttributes = [fileManager fileAttributesAtPath:filePath traverseLink:YES];
        if (fileAttributes != nil) {
            NSDate *creationDate=[fileAttributes objectForKey:NSFileCreationDate];
            if (creationDate) {
                NSDateFormatter *dateFomatter = [[NSDateFormatter alloc] init];
                dateFomatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
                // 当前时间字符串格式
                NSString *formatDate = [dateFomatter stringFromDate:creationDate];
                //                NSString *createTime=[formatDate substringToIndex:10];
                //不是当天 删除文件
                //                if(![createTime isEqualToString:[LSUtility dateNow]]){
                //                    if ([fileManager removeItemAtPath:filePath error:NULL]) {
                //                        //NSLog(@"删除文件成功");
                //                    }
                //                }
                
                //相差24小时 删除
                long timeC=[LSUtility timeDifferenceByTimeDel:formatDate];
                //                DeLog(@"文件时差：%ld",timeC);
                
                if(timeC<=-24){
                    if ([fileManager removeItemAtPath:filePath error:NULL]) {
                        NSLog(@"删除文件成功");
                    }
                }
                
            }
        }
    }
}

//查询项目唯一总监
+ (NSString *)directorFromProject {
    NSString *sqlStr=[NSString stringWithFormat:@"select USER_ID from PROJECT_USER where USER_TYPE ='USER_01' and pro_id='%@'",PROID];
    FMDatabase *db=[FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    [db open];
    
    FMResultSet *resule=[db executeQuery:sqlStr];
    NSString *userID;
    while ([resule next]) {
        userID =[resule stringForColumn:@"USER_ID"];
    }
    [db close];
    return userID;
}

//根据人员 查询该人员所属单位是否是监理单位
+ (BOOL)queryUnitIsSuperVisionbyUserID:(NSString *)userID{
    NSString *sqlStr=[NSString stringWithFormat:@" select IS_SUPERVISION_UNIT from unit where id= (select unit from USER where id='%@')",userID];
    
    FMDatabase *db=[FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    
    [db open];
    FMResultSet *resule=[db executeQuery:sqlStr];
    
    NSInteger iS_SUPERVISION_UNIT=0;
    while ([resule next]) {
        
        iS_SUPERVISION_UNIT= [resule intForColumn:@"IS_SUPERVISION_UNIT"];
    }
    if(iS_SUPERVISION_UNIT ==0){
        return NO;
    }else{
        return YES;
    }
}

//查询广告表 +条数
+ (NSMutableArray *)queryAdvertiseMent:(BOOL)isAll{
    
    FMDatabase *db=[FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    
    [db open];
    NSString *sqlStr=@"";
    if(isAll){
        sqlStr=@"select * FROM ADVERTISING_PICTURE ORDER BY state ASC, sort DESC, createtime DESC";
    }else{
        sqlStr=@"select * FROM ADVERTISING_PICTURE WHERE advertisementType='1' ORDER BY state ASC, sort DESC, createtime DESC ";
    }
    
    FMResultSet *resule=[db executeQuery:sqlStr];
    
    NSMutableArray *advArr=[NSMutableArray array];
    
    while ([resule next]) {
        NSDictionary *dic=[resule resultDictionary];
        [advArr addObject:dic];
    }
    
    [db close];
    return advArr;
}


//查询广告表
+ (NSMutableArray *)queryAllAdvertiseMent{
    
    FMDatabase *db=[FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    
    [db open];
    //查询所有广告
    NSString *sqlStr=@"select * FROM ADVERTISING_PICTURE ORDER BY state ASC, sort DESC, CREATE_TIME DESC";
    
    FMResultSet *resule=[db executeQuery:sqlStr];
    
    NSMutableArray *advArr=[NSMutableArray array];
    
    while ([resule next]) {
        NSDictionary *dic=[resule resultDictionary];
        //判断此条广告是不是只能监理单位查看
        NSString *range=[resule stringForColumn:@"display_range"];
        if(range){
            //只能监理单位下的人添加
            if([range isEqualToString:@"1"]){
                if([LSUtility queryUnitIsSuperVisionbyUserID:USERID]){
                    [advArr addObject:dic];
                }
            }else if([range isEqualToString:@"0"]||[range isEqualToString:@""]){
                //直接添加
                [advArr addObject:dic];
            }
        }else{
            [advArr addObject:dic];
        }
    }
    [db close];
    return advArr;
}

//查询施工单位
+(NSMutableArray *)constructionUnitFromProId:(NSString *)proId{
    
    NSString *sqlStr=[NSString stringWithFormat:@"SELECT PRO_UNIT_NAME FROM PROJECT_UNIT where pro_id='%@' and PRO_UNIT_TYPE='UNIT_02'",proId];
    
    FMDatabase *db=[FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    
    [db open];
    FMResultSet *resule=[db executeQuery:sqlStr];
    
    NSMutableArray *unitArr=[NSMutableArray array];
    
    while ([resule next]) {
        
        NSString *unitName= [resule stringForColumn:@"PRO_UNIT_NAME"];
        
        [unitArr addObject:unitName];
    }
    
    [db close];
    
    return unitArr;
}


//根据图片名和流程记录删掉附件
+(BOOL)delAttachmentForFileId:(NSString *)fileID fileName:(NSString *)imageName{
    FMDatabase *db = [FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    [db open];
    NSString *sqlStr=[NSString stringWithFormat:@"update attachment set LOCAL_MODIFY_STATE='DEL' where file_id='%@' and FILE_NAME='%@'",fileID,imageName];
    BOOL isok=[db executeUpdate:sqlStr];
    [db close];
    return isok;
}

//查询附件详情
+ (NSMutableDictionary *)queryAttachment:(NSString *)fileID{
    
    FMDatabase *db=[FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    DBHelper *dbhelp= [DBHelper help];
    
    NSDictionary *Column=@{
                           @"ID":@"text",
                           @"FILE_ID":@"text",
                           @"FILE_TYPE_ID":@"text",
                           @"FILE_NAME":@"text",
                           @"FILE_DESC":@"text",
                           @"PRO_ID":@"text",
                           @"EXTEND_INFO":@"text",
                           @"CREATE_TIME":@"text",
                           @"CREATE_USER_NAME":@"text",
                           };
    NSMutableDictionary *fileMuDic;
    if(fileID){
        NSArray *fileArray=[dbhelp DataBase:db selectKeyTypes:Column fromTable:ATTACHMENT whereCondition:@{@"ID":fileID}];
        if(fileArray.count>0){
            fileMuDic=[fileArray lastObject];
        }
    }
    return fileMuDic;
}


//同步日志到本地 入参2
+(NSMutableString *)parameterDownLoadWorkLogProIds{
    
    NSMutableArray *logArr=[LSUtility queryProsByUserId:USERID];
    logArr = [logArr valueForKeyPath:@"@distinctUnionOfObjects.self"];
    NSString *logJson=[LSUtility dictionaryToJson_2:logArr];
    
    NSMutableString *mutStr = [NSMutableString
                               stringWithString:logJson];
    
    NSRange range1 = {0,logJson.length};
    [mutStr replaceOccurrencesOfString:@"\""
                            withString:@"'"
                               options:NSLiteralSearch range:range1];
    NSRange range2 = {0,mutStr.length};
    [mutStr replaceOccurrencesOfString:@"["
                            withString:@""
                               options:NSLiteralSearch range:range2];
        NSRange range3 = {0,mutStr.length};
    [mutStr replaceOccurrencesOfString:@"]"
                            withString:@""
                               options:NSLiteralSearch range:range3];
    
    return mutStr;
}

// 获取项目人员数据  传递一个数组 新挡下的的proid
+ (NSMutableArray *)getProjectUser:(NSString *)flag proIds:(NSMutableArray*)proIds{
    
    FMDatabase *db = [FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    [db open];
    NSString *detailSql;
    if([flag isEqualToString:@"proUsers"]){
        detailSql = [NSString stringWithFormat:@" SELECT pro_id,COUNT(*) as count, max(MODIFY_TIME) as modifytime,max(CREATE_TIME) as createtime FROM PROJECT_USER GROUP BY PRO_ID ORDER BY MODIFY_TIME desc"];
    }else if ([flag isEqualToString:@"add"]){
        detailSql = [NSString stringWithFormat:@" SELECT pro_id,COUNT(*) as count, max(MODIFY_TIME) as modifytime,max(CREATE_TIME) as createtime FROM address GROUP BY PRO_ID ORDER BY MODIFY_TIME desc"];
    }else {
        detailSql = [NSString stringWithFormat:@" SELECT pro_id,COUNT(*) as count, max(MODIFY_TIME) as modifytime,max(CREATE_TIME) as createtime FROM project_unit GROUP BY PRO_ID ORDER BY MODIFY_TIME desc"];
    }
    
    FMResultSet *detailResult = [db executeQuery:detailSql];
    NSMutableArray *arr=[NSMutableArray array];
    while ([detailResult next]) {
        NSMutableDictionary *dic = [NSMutableDictionary dictionary];
        NSString *proid=[detailResult stringForColumn:@"pro_id"];
        NSString *count = [detailResult stringForColumn:@"count"];
        NSString *modifyTime = [detailResult stringForColumn:@"modifytime"];
        NSString *createTime = [detailResult stringForColumn:@"createtime"];
        [dic setObject:proid forKey:@"proId"];
        
        if([flag isEqualToString:@"proUsers"]){
            [dic setObject:count forKey:@"userCnt"];
        }else if([flag isEqualToString:@"add"]){
            [dic setObject:count forKey:@"addrCnt"];
        }
        else{
            [dic setObject:count forKey:@"unitCnt"];
        }
        [dic setObject:[modifyTime isEqualToString:@""]?createTime:modifyTime forKey:@"modifyTime"];
        [arr addObject:dic];
    }
    //本地未查询到数据
    if(arr.count==0){
        NSMutableDictionary *dic = [NSMutableDictionary dictionary];
        [dic setObject:PROID forKey:@"proId"];
        if([flag isEqualToString:@"proUsers"]){
            [dic setObject:@"0" forKey:@"userCnt"];
        }else if([flag isEqualToString:@"add"]){
            [dic setObject:@"0" forKey:@"addCnt"];
        }
        else{
            [dic setObject:@"0" forKey:@"unitCnt"];
        }
        [arr addObject:dic];
    }else{
        if(proIds.count>0){
            for (NSString *idStr in proIds) {
                if([flag isEqualToString:@"proUsers"]){
                    //新增一个其他的项目
                    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
                    [dic setObject:idStr forKey:@"proId"];
                    [dic setObject:@"0" forKey:@"userCnt"];
                    [dic setObject:@"" forKey:@"modifyTime"];
                    [arr addObject:dic];
                }else if([flag isEqualToString:@"add"]){
                    //新增一个其他的项目
                    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
                    [dic setObject:idStr forKey:@"proId"];
                    [dic setObject:@"0" forKey:@"addrCnt"];
                    [dic setObject:@"" forKey:@"modifyTime"];
                    [arr addObject:dic];
                    
                }
                else{  //新增一个其他的项目
                    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
                    [dic setObject:idStr forKey:@"proId"];
                    [dic setObject:@"0" forKey:@"unitCnt"];
                    [dic setObject:@"" forKey:@"modifyTime"];
                    [arr addObject:dic];
                }
            }
        }
    }
    return arr;
}


//判断项目id  本地是否存在
+ (BOOL)queryProjectForId:(NSString *)proId{
    
    // 获取数据库
    FMDatabase *db = [FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    // 打开数据库
    if (![db open]) {
        [db open];
    }
    // 准备sql语句
    NSString *sql = [NSString stringWithFormat:@"SELECT ID FROM PROJECT WHERE ID = '%@'", proId];
    // 查找数据
    FMResultSet *result = [db executeQuery:sql];
    NSMutableArray *array = [NSMutableArray array];
    
    while ([result next]) {
        NSString *ID = [result stringForColumn:@"ID"];
        [array addObject:ID];
    }
    //存在和本地一样的数据 返回yes
    if(array.count>0){
        return NO;
    }else{
        return YES;
    }
}

// 用""替换其他符号
+ (NSMutableString *)strbydan:(NSString *)str{
    NSMutableString *mutStr = [NSMutableString
                               stringWithString:str];
    
    NSRange range1 = {0,str.length};
    [mutStr replaceOccurrencesOfString:@"\""
                            withString:@""
                               options:NSLiteralSearch range:range1];
    
    NSRange range2 = {0,mutStr.length};
    [mutStr replaceOccurrencesOfString:@"["
                            withString:@""
                               options:NSLiteralSearch range:range2];
    
    NSRange range3 = {0,mutStr.length};
    [mutStr replaceOccurrencesOfString:@"]"
                            withString:@""
                               options:NSLiteralSearch range:range3];
    return mutStr;
}


/*
 *  查询巡检流程表ID 根据项目关联的巡检流程
 */
+ (NSString *)queryInspectProcessIds{
    FMDatabase *db=[FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    
    DBHelper *helper=[DBHelper help];
    
    NSArray *dataArr= [helper DataBase:db selectKeyTypes:@{@"ID":@"text"} fromTable:INSPECT_PROCESS];
    
    //id存入数组
    NSMutableArray *idArray=[NSMutableArray array];
    
    if(dataArr.count>0){
        for (NSDictionary *dic in dataArr) {
            [idArray addObject:[dic objectForKey:@"ID"]];
        }
    }
    NSString *idsStr=[LSUtility dictionaryToJson_2:idArray];
    return idsStr;
}

//查询所有附件详情
+(NSArray *)queryAllAttachment:(NSString *)fileID{
    NSString *sqlStr=[NSString stringWithFormat:@"SELECT * FROM ATTACHMENT where FILE_ID='%@' and LOCAL_MODIFY_STATE!='DEL'",fileID];
    
    FMDatabase *db=[FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    
    [db open];
    FMResultSet *resule=[db executeQuery:sqlStr];
    NSMutableArray *attachArr=[NSMutableArray array];
    
    while ([resule next]) {
        NSDictionary *dic=[resule resultDictionary];
        [attachArr addObject:dic];
    }
    [db close];
    return attachArr;
}

//广告查询附件id
+(NSDictionary *)queryAdvAttachment:(NSString *)advID{
    NSString *sqlStr=[NSString stringWithFormat:@"SELECT * FROM ATTACHMENT where FILE_ID='%@' and LOCAL_MODIFY_STATE!='DEL'",advID];
    FMDatabase *db=[FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    
    [db open];
    FMResultSet *resule=[db executeQuery:sqlStr];
    NSDictionary *dic;
    while ([resule next]) {
        dic=[resule resultDictionary];
    }
    [db close];
    if(dic){
        return dic;
    }else{
        NSLog(@"广告附件表不存在:%@",advID);
        return nil;
    }
}

//得到项目中 工程概览的城市
+(NSMutableDictionary *)queryProengineerSurvey:(NSString *)proId{
    FMDatabase *db = [FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    [db open];
    NSString *sqlStr=[NSString stringWithFormat:@"select * from PRO_ENGINEER_SURVEY where pro_id='%@'",proId];
    FMResultSet *resule=[db executeQuery:sqlStr];
    
    NSMutableDictionary *city = [NSMutableDictionary dictionary];
    
    while ([resule next]) {
        NSDictionary *dic = [resule resultDictionary];
        NSLog(@"%@",dic);
        NSString *city_code=[resule stringForColumn:@"city_code"];
        NSString *address =[resule stringForColumn:@"ENGINEER_ADDRESS"];
        
        [city setObject:address forKey:city_code];
    }
    [db close];
    return city;
}

//根据当前id查询到流程表相关联的项目id
+(NSString *)getProcessProIdByRecordID:(NSString *)recordId{
    FMDatabase *db = [FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    [db open];
    NSString *sqlStr=[NSString stringWithFormat:@"select pro_id from inspect_process where ID=(select INSPECT_PROCESS_ID from inspect_process_record where id='%@')",recordId];
    FMResultSet *resule=[db executeQuery:sqlStr];
    NSString *ids;
    while ([resule next]) {
        ids=[resule stringForColumn:@"pro_id"];
    }
    [db close];
    return ids;
}

//传入当前记录id 查询该流程任务下指定状态下的 id
+(NSString *)queryInspectStateId:(NSString *)recordId state:(NSString *)state{
    FMDatabase *db = [FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    [db open];
    NSString *sqlStr=[NSString stringWithFormat:@"select ID from inspect_process_record where INSPECT_USER_ITEM_ID=(select INSPECT_USER_ITEM_ID from inspect_process_record where id='%@') and inspect_item_state='%@' order by (create_time)",recordId,state];
    FMResultSet *resule=[db executeQuery:sqlStr];
    NSString *ids;
    while ([resule next]) {
        ids=[resule stringForColumn:@"ID"];
    }
    [db close];
    return ids;
}

//查询该巡检流程中图片是否已经存在
+(BOOL)queryInspectProcessRFileName:(NSString *)fileName fileId:(NSString *)fileId{
    FMDatabase *db = [FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    [db open];
    
    NSString *sqlStr=[NSString stringWithFormat:@"select * from attachment where file_id='%@' and FILE_NAME='%@'",fileId,fileName];
    FMResultSet *resule=[db executeQuery:sqlStr];
    NSMutableArray *arr=[NSMutableArray array];
    while ([resule next]) {
        NSString *ids=[resule stringForColumn:@"ID"];
        [arr addObject:ids];
    }
    [db close];
    
    if(arr.count>0){
        return YES;
    }else{
        return NO;
    }
}

//记录表新增数据
+(BOOL)insertAttachmentFromFileID:(NSString *)fileID andTableID:(NSString *)ids andImage:(UIImage *)image andType:(NSString *)type andImageName:(NSString *)imageName{
    
    FMDatabase *db = [FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    DBHelper *dbhelper = [DBHelper help];
    
    NSDictionary *pragameDic = [NSDictionary dictionary];
    
    NSDate *senddate=[NSDate date];
    NSDateFormatter *dateformatter=[[NSDateFormatter alloc] init];
    [dateformatter setDateFormat:@"yyyyMMdd HH:mm:ss"];
    NSString *locationString=[dateformatter stringFromDate:senddate];
    
    NSString *filePath = [NSString stringWithFormat:@"/%@/%@.png",locationString,imageName];
    
    pragameDic = @{
                   @"ID":ids,
                   //文件所属记录类型
                   @"FILE_TYPE_ID":type,
                   //文件所属记录
                   @"FILE_ID":fileID,
                   //所属项目
                   @"PRO_ID":PROID,
                   //文件名称
                   @"FILE_NAME":imageName,
                   //文件大小
                   @"FILE_SIZE":@"0",
                   //文件后缀名
                   @"FILE_SUFFIX":@".png",
                   //文件路径
                   @"FILE_PATH":filePath,
                   @"FILE_DESC":@"",
                   //附件状态
                   @"FILE_STATE":@"1",
                   //扩展信息
                   @"EXTEND_INFO":@"",
                   //创建人
                   @"CREATE_USER_NAME":@"anonymous",
                   //创建时间
                   @"CREATE_TIME":[LSUtility dateNow],
                   //创建IP
                   @"CREATE_IP":[LSUtility getIPAddress],
                   @"MODIFY_USER_NAME":@"",
                   @"MODIFY_IP":@"",
                   @"MODIFY_TIME":@"",
                   @"LOCAL_MODIFY_USER_NAME":@"",
                   @"LOCAL_MODIFY_TIME":@"",
                   @"LOCAL_MODIFY_STATE":@"ADD"
                   };
    
    BOOL isAdd=[dbhelper DataBase:db insertReplaceKeyValues:pragameDic intoTable:ATTACHMENT];
    
    if(isAdd) {
        return YES;
    }else{
        return NO;
    }
    
}

/*
 *  旁站批量存储
 */

// 记录表新增数据
+ (BOOL)insertAttachmentFromSiteFileID:(NSString *)fileID andTableID:(NSString *)ids andImage:(UIImage *)image andType:(NSString *)type andImageName:(NSString *)imageName andfileChildType:(NSString *)fileChildType{
    
    FMDatabase *db = [FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    DBHelper *dbhelper = [DBHelper help];
    
    NSDictionary *pragameDic = [NSDictionary dictionary];
    
    NSDate *senddate=[NSDate date];
    NSDateFormatter *dateformatter=[[NSDateFormatter alloc] init];
    [dateformatter setDateFormat:@"yyyyMMdd"];
    NSString *locationString=[dateformatter stringFromDate:senddate];
    //拼接路径
    NSString *filePath = [NSString stringWithFormat:@"/%@/%@",locationString,imageName];
    //拼接childType
    NSDictionary *childDic=@{@"fileChildType":fileChildType};
    NSString *EXTEND_INFO=[LSUtility dictionaryToJson_2:childDic];
    
    pragameDic = @{
                   @"ID":ids,
                   @"FILE_TYPE_ID":type,
                   @"FILE_ID":fileID,
                   @"PRO_ID":PROID,
                   @"FILE_NAME":imageName,
                   @"FILE_SIZE":[LSUtility imageDataLenth:image],
                   @"FILE_SUFFIX":@".png",
                   @"FILE_PATH":filePath,
                   @"FILE_DESC":@"",
                   @"FILE_STATE":@"1",
                   @"EXTEND_INFO":EXTEND_INFO,
                   //创建人
                   @"CREATE_USER_NAME":@"anonymous",
                   //创建时间
                   @"CREATE_TIME":[LSUtility dateNow],
                   //创建IP
                   @"CREATE_IP":[LSUtility getIPAddress],
                   @"MODIFY_USER_NAME":@"",
                   @"MODIFY_IP":@"",
                   @"MODIFY_TIME":@"",
                   @"LOCAL_MODIFY_USER_NAME":@"",
                   @"LOCAL_MODIFY_TIME":@"",
                   //
                   @"LOCAL_MODIFY_STATE":@"ADD"
                   };
    BOOL isAdd=[dbhelper DataBase:db insertReplaceKeyValues:pragameDic intoTable:ATTACHMENT];
    if(isAdd) {
        return YES;
    }else{
        return NO;
    }
    
}

//旁站附件批量存
+ (NSMutableArray *)insertAttachmentSiteFromArray:(NSMutableArray *)fileArr andRecordId:(NSString *)recordId andType:(NSString *)type andChildType:(NSString *)childType{
    
    NSMutableArray *arrForDic=[NSMutableArray array];
    
    for (int i=0; i<fileArr.count; i++) {
        //创建附件Id
        NSString *ids=[NSUUID UUID].UUIDString;
        
        NSArray *arr=[fileArr[i] componentsSeparatedByString:@"/"];
        //得到图片名称
        NSString *imageName = [arr lastObject];
        //得到图片
        UIImage *image=[UIImage imageWithContentsOfFile:fileArr[i]];
        
        //存入附件表
        [self insertAttachmentFromSiteFileID:recordId andTableID:ids andImage:image andType:type andImageName:imageName  andfileChildType:childType];
        
        //返回存入关联记录表
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        [dict setObject:ids forKey:@"fileId"];
        [dict setObject:@"1" forKey:@"fileState"];
        
        [arrForDic addObject:dict];
    }
    return  arrForDic;
}

//旁站 判断附件在该记录该模块下是否存在
+ (BOOL)isExistFileFormWorkRecord:(NSString *)recordId andFilePath:(NSString *)filePath andChildType:(NSString *)childType{
    
    NSString *sqlStr=[NSString stringWithFormat:@"SELECT ID FROM ATTACHMENT where FILE_ID='%@' AND FILE_PATH='%@' AND EXTEND_INFO='%@'",recordId,filePath,childType];
    
    FMDatabase *db=[FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    
    [db open];
    FMResultSet *resule=[db executeQuery:sqlStr];
    
    NSMutableArray*arr=[NSMutableArray array];
    
    while ([resule next]) {
        [arr addObject: [resule stringForColumn:@"ID"]];
    }
    [db close];
    
    if(arr.count>0){
        return YES;
    }
    return NO;
}


// 本地附件新增
+ (NSMutableArray *)insertAttachmentFromArray:(NSMutableArray *)fileArr andRecordId:(NSString *)recordId andType:(NSString *)type andRecifyState:(NSString *)recifyState {
    
    NSMutableArray *arrForDic=[NSMutableArray array];
    
    for (int i = 0; i < fileArr.count; i++) {
        NSString *ids=[NSUUID UUID].UUIDString;
        
        NSArray *arr=[fileArr[i] componentsSeparatedByString:@"/"];
        
        NSString *imageName = [arr lastObject];
        
        UIImage *image=[UIImage imageWithContentsOfFile:fileArr[i]];
        
        //存入附件表
        [self insertAttachmentFlowRecordFromFileID:recordId andTableID:ids andImage:image andType:type andImageName:imageName andRecifyState:recifyState];
        
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        [dict setObject:ids forKey:@"fileId"];
        [dict setObject:recifyState forKey:@"fileState"];
        
        [arrForDic addObject:dict];
    }
    return  arrForDic;
}

// 附件表新增数据
+ (BOOL)insertAttachmentFlowRecordFromFileID:(NSString *)fileID andTableID:(NSString *)ids andImage:(UIImage *)image andType:(NSString *)type andImageName:(NSString *)imageName andRecifyState:(NSString *)recifyState {
    
    FMDatabase *db = [FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    DBHelper *dbhelper = [DBHelper help];
    
    NSDictionary *pragameDic = [NSDictionary dictionary];
    
    NSDate *senddate=[NSDate date];
    NSDateFormatter *dateformatter=[[NSDateFormatter alloc] init];
    [dateformatter setDateFormat:@"yyyyMMdd"];
    NSString *locationString=[dateformatter stringFromDate:senddate];
    //拼接路径
    NSString *filePath = [NSString stringWithFormat:@"/%@/%@.png",locationString,imageName];
    //拼接childType
    NSDictionary *recifyDic = @{@"recifyState":recifyState, @"recifyRelationId":fileID};
    NSDictionary *extendInfoDic = @{@"fileChildType":@"", @"recify":recifyDic};
    NSString *EXTEND_INFO=[LSUtility dictionaryToJson_2:extendInfoDic];
    pragameDic = @{
                   @"ID":ids,
                   //文件所属记录类型
                   @"FILE_TYPE_ID":type,
                   //文件所属记录
                   @"FILE_ID":fileID,
                   //所属项目
                   @"PRO_ID":PROID,
                   //文件名称
                   @"FILE_NAME":imageName,
                   //文件大小
                   @"FILE_SIZE":[LSUtility imageDataLenth:image],
                   //文件后缀名
                   @"FILE_SUFFIX":@".png",
                   //文件路径
                   @"FILE_PATH":filePath,
                   @"FILE_DESC":@"",
                   //附件状态
                   @"FILE_STATE":@"0",
                   //扩展信息
                   @"EXTEND_INFO":EXTEND_INFO,
                   //创建人
                   @"CREATE_USER_NAME":DEF_PERSISTENT_GET_OBJECT(@"realname"),
                   //创建时间
                   @"CREATE_TIME":[LSUtility dateNow],
                   //创建IP
                   @"CREATE_IP":[LSUtility getIPAddress],
                   @"MODIFY_USER_NAME":@"",
                   @"MODIFY_IP":@"",
                   @"MODIFY_TIME":@"",
                   @"LOCAL_MODIFY_USER_NAME":@"",
                   @"LOCAL_MODIFY_TIME":@"",
                   @"LOCAL_MODIFY_STATE":@"ADD"
                   };
    BOOL isAdd=[dbhelper DataBase:db insertReplaceKeyValues:pragameDic intoTable:ATTACHMENT];
    if(isAdd) {
        
        return YES;
    }else{
        return NO;
    }
}


/*
 *  见证取样 二维码存附件表extendInfo字段
 */
// 本地附件新增
+ (NSMutableArray *)insertAttachmentFromArray:(NSMutableArray *)fileArr andRecordId:(NSString *)recordId andType:(NSString *)type andRecifyState222:(NSString *)recifyState withCodeArr:(NSMutableArray *)codeArr {
    
    NSMutableArray *arrForDic=[NSMutableArray array];
    
    for (int i = 0; i < fileArr.count; i++) {
        NSString *ids=[NSUUID UUID].UUIDString;
        
        NSArray *arr=[fileArr[i] componentsSeparatedByString:@"/"];
        
        NSString *imageName = [arr lastObject];
        
        UIImage *image=[UIImage imageWithContentsOfFile:fileArr[i]];
        
        //存入附件表
        [self insertAttachmentFlowRecordFromFileID:recordId andTableID:ids andImage:image andType:type andImageName:imageName andRecifyState222:recifyState withcode:codeArr[i]];
        
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        [dict setObject:ids forKey:@"fileId"];
        [dict setObject:recifyState forKey:@"fileState"];
        
        [arrForDic addObject:dict];
    }
    return  arrForDic;
}


// 附件表新增数据
+ (BOOL)insertAttachmentFlowRecordFromFileID:(NSString *)fileID andTableID:(NSString *)ids andImage:(UIImage *)image andType:(NSString *)type andImageName:(NSString *)imageName andRecifyState222:(NSString *)recifyState  withcode:(NSString *)code{
    
    FMDatabase *db = [FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    DBHelper *dbhelper = [DBHelper help];
    
    NSDictionary *pragameDic = [NSDictionary dictionary];
    
    NSDate *senddate=[NSDate date];
    NSDateFormatter *dateformatter=[[NSDateFormatter alloc] init];
    [dateformatter setDateFormat:@"yyyyMMdd"];
    NSString *locationString=[dateformatter stringFromDate:senddate];
    //拼接路径
    NSString *filePath = [NSString stringWithFormat:@"/%@/%@.png",locationString,imageName];
    
    NSString *EXTEND_INFO=code;
    
    pragameDic = @{
                   @"ID":ids,
                   //文件所属记录类型
                   @"FILE_TYPE_ID":type,
                   //文件所属记录
                   @"FILE_ID":fileID,
                   //所属项目
                   @"PRO_ID":PROID,
                   //文件名称
                   @"FILE_NAME":imageName,
                   //文件大小
                   @"FILE_SIZE":[LSUtility imageDataLenth:image],
                   //文件后缀名
                   @"FILE_SUFFIX":@".png",
                   //文件路径
                   @"FILE_PATH":filePath,
                   @"FILE_DESC":@"",
                   //附件状态
                   @"FILE_STATE":@"0",
                   //扩展信息
                   @"EXTEND_INFO":EXTEND_INFO,
                   //创建人
                   @"CREATE_USER_NAME":DEF_PERSISTENT_GET_OBJECT(@"realname"),
                   //创建时间
                   @"CREATE_TIME":[LSUtility nowTime],
                   //创建IP
                   @"CREATE_IP":[LSUtility getIPAddress],
                   @"MODIFY_USER_NAME":@"",
                   @"MODIFY_IP":@"",
                   @"MODIFY_TIME":@"",
                   @"LOCAL_MODIFY_USER_NAME":@"",
                   @"LOCAL_MODIFY_TIME":@"",
                   @"LOCAL_MODIFY_STATE":@"ADD"
                   };
    BOOL isAdd=[dbhelper DataBase:db insertReplaceKeyValues:pragameDic intoTable:ATTACHMENT];
    if(isAdd) {
        //附件上传
        //        DataSynchronization  *sync=[[DataSynchronization alloc]init];
        //        [sync uploadAttachsBackground];
        return YES;
    }else{
        return NO;
    }
}




//根据记录表 和 EXTEND_INFO 查询附件id

+(NSMutableArray *)queryAttachmentFormfileId:(NSString *)fileId andExtend:(NSString *)extendInfo andFilePathArr:(NSArray *)filePathArr{
    FMDatabase *db = [FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    [db open];
    //filePathArr 字典中id 提取
    NSMutableArray *idArr=[NSMutableArray array];
    for (NSDictionary *dic in filePathArr) {
        [idArr addObject:[dic objectForKey:@"fileId"]];
    }
    NSString *pathArrS=[self dictionaryToJson_2:idArr];
    NSString *pathArrStr=[self SymbolConversion:pathArrS];
    
    NSString *sqlStr = [NSString stringWithFormat:@"SELECT FILE_NAME FROM ATTACHMENT WHERE FILE_ID='%@' AND EXTEND_INFO='%@' AND ID IN %@",fileId,extendInfo,pathArrStr];
    
    FMResultSet *resule=[db executeQuery:sqlStr];
    NSMutableArray *arr=[NSMutableArray array];
    while ([resule next]) {
        NSString *ids=[resule stringForColumn:@"FILE_NAME"];
        [arr addObject:ids];
    }
    [db close];
    return arr;
}


//见证取样 判断其他端口是否做了操作
+(BOOL)sampleProcessRecordIsOperationFromId:(NSString *)ProcessId{
    FMDatabase *db = [FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    [db open];
    NSString *sqlStr=[NSString stringWithFormat:@"select * FROM SAMPLE_PROCESS_RECORD where PROCESS_ID='%@'",ProcessId];
    FMResultSet *resule=[db executeQuery:sqlStr];
    NSMutableArray *arr=[NSMutableArray array];
    while ([resule next]) {
        NSString *ids=[resule stringForColumn:@"ID"];
        [arr addObject:ids];
    }
    [db close];
    if(arr.count>=2){
        return YES;
    }else{
        return NO;
    }
}

//查询附件
+(NSMutableArray *)quertFileImageType:(NSString *)type andId:(NSString *)recordId andFilePathArr:(NSArray *)fileArr{
    //查询附件表
    NSDictionary *dic=@{@"fileChildType":type};
    NSString *jsonStr=[LSUtility dictionaryToJson_2:dic];
    NSMutableArray *nameArr=[LSUtility queryAttachmentFormfileId:recordId andExtend:jsonStr andFilePathArr:fileArr];
    NSMutableArray *imageArr=[NSMutableArray array];
    if(nameArr.count>0){
        for (NSString *name in nameArr) {
            NSString *filePath=[DEF_FILE_PATH stringByAppendingString:
                                [NSString stringWithFormat:@"/%@",name]];
            [imageArr addObject:filePath];
        }
    }
    return imageArr;
}

// 查找图片路径
+ (NSString *)checkImagePath:(NSString *)ID {
    FMDatabase *db=[FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    [db open];
    NSString *sql = [NSString stringWithFormat:@"SELECT FILE_NAME, FILE_PATH FROM ATTACHMENT WHERE ID = '%@'", ID];
    FMResultSet *result = [db executeQuery:sql];
    NSString *fileName;
    while ([result next]) {
        fileName = [result stringForColumn:@"FILE_NAME"];
    }
    [db close];
    return fileName;
}

//根据图片名称 得到图片
+(UIImage *)getImageByFileName:(NSString *)fileName{
    NSString *tempPath=[DEF_FILE_PATH stringByAppendingString:[NSString stringWithFormat:@"/%@",fileName]];
    
    UIImage *image=[UIImage imageWithContentsOfFile:tempPath];
    
    if(!image){
        image=[UIImage imageNamed:@"plugin_camera_no_pictures"];
    }
    return image;
}

// 根据图片名称 得到图片(如果为空,返回nil)
+(UIImage *)getImageByFileName2:(NSString *)fileName{
    NSString *tempPath=[DEF_FILE_PATH stringByAppendingString:[NSString stringWithFormat:@"/%@",fileName]];
    UIImage *image=[UIImage imageWithContentsOfFile:tempPath];
    return image;
}

// 根据图片名称 得到图片地址(如果为空,返回nil)
+(NSString *)getImagePath:(NSString *)fileName {
    NSString *tempPath=[DEF_FILE_PATH stringByAppendingString:[NSString stringWithFormat:@"/%@",fileName]];
    return tempPath;
}

// 时间差
+ (NSTimeInterval)getDifftimeByTime:(NSString *)endTime {
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSDate *date = [dateFormatter dateFromString:endTime];
    NSTimeInterval  timeInterval = [date timeIntervalSinceNow];
    return timeInterval;
}

//监理查询当天日记是否审阅 审阅不能添加
+(BOOL)jianliQueryDiaryReView{
    
    FMDatabase *db = [FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    [db open];
    NSString *sqlStr=[NSString stringWithFormat:@"select * from WORK_DIARY where pro_id='%@' and DIARY_USER='%@' and REVIEW_STATE='1' and substr(DIARY_TIME,1,10)='%@'",PROID,USERID,[LSUtility dateNow]];
    FMResultSet *resule=[db executeQuery:sqlStr];
    NSMutableArray *arr=[NSMutableArray array];
    while ([resule next]) {
        NSString *ids=[resule stringForColumn:@"id"];
        [arr addObject:ids];
    }
    [db close];
    if(arr.count>0){
        return YES;
    }else{
        return NO;
    }
}

//
//UIDevice *device = [UIDevice currentDevice];//创建设备对象
//NSUUID *UUID = [device identifierForVendor];
//NSString *deviceID = [UUID UUIDString];
//NSLog(@"UUID:%@",deviceID);

/*
 * -------------  二期  ------------------
 */
//得到所有巡检检查类
+ (NSArray *)getInspectTimeCategory {
    FMDatabase *db=[FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    DBHelper *dbhelp= [DBHelper help];
    NSArray *typeArr=[dbhelp DataBase:db selectKeyTypes:@{@"ID":@"text",@"INSPECT_NAME":@"text"} fromTable:INSPECT_ITEM whereCondition:@{@"PARENT_ID":@"0"}];
    
    return typeArr;
}

//根据人员查到相关巡检的项目
+(NSMutableArray *)quertProIdByInspectId:(NSString *)userID{
    FMDatabase *db = [FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    [db open];
    NSString *sqlStr=[NSString stringWithFormat:@"SELECT distinct(IGU.id) as aa,ip.PRO_ID AS proId,IGU.inspect_user_type as type,IGU.* FROM INSPECT_GROUP_USER IGU LEFT JOIN USER U ON IGU.INSPECT_USER_ID=U.ID LEFT JOIN inspect_group insg ON insg.id=IGU.inspect_group_id LEFT JOIN inspect_process ip ON ip.inspect_group_id=IGU.inspect_group_id where IGU.INSPECT_USER_ID='%@'",userID];
    FMResultSet *resule=[db executeQuery:sqlStr];
    NSMutableArray *arr=[NSMutableArray array];
    while ([resule next]) {
        NSString *ids=[resule stringForColumn:@"proId"];
        //        NSString *type=[resule stringForColumn:@"type"];
        //        NSDictionary *dic=@{@"ids":ids,@"type":type};
        
        //        if([type isEqualToString:DEFROLE]){
        //            continue;
        //        }
        if(ids){
            [arr addObject:ids];
        }
    }
    [db close];
    return arr;
}

//查询巡检流程记录表表记录表 人
+ (NSString *)getInspectUserName:(NSString *)processId{
    FMDatabase *db=[FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    DBHelper *dbhelp= [DBHelper help];
    NSArray *typeArr=[dbhelp DataBase:db selectKeyTypes:@{@"ID":@"text",@"INSPECT_USER_ID":@"text"} fromTable:INSPECT_PROCESS_RECORD whereCondition:@{@"ID":processId}];
    NSDictionary *dic=[typeArr firstObject];
    return dic[@"INSPECT_USER_ID"];
}

//查询该流程下 所有的巡检项
+(NSMutableArray *)getAllItemIdByProcess:(NSString *)processId{
    FMDatabase *db = [FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    [db open];
    NSString *sqlStr=[NSString stringWithFormat:@"select INSPECT_ITEM_ID from inspect_process_record where INSPECT_PROCESS_ID='%@' and INSPECT_USER_ITEM_ID !=''",processId];
    FMResultSet *resule=[db executeQuery:sqlStr];
    NSMutableArray *arr=[NSMutableArray array];
    while ([resule next]) {
        NSString *ids=[resule stringForColumn:@"INSPECT_ITEM_ID"];
        [arr addObject:ids];
    }
    [db close];
    return arr;
}

//查询该流程下 所有自己的巡检项
+(NSMutableArray *)getAllItemIdByProcessMy:(NSString *)processId{
    FMDatabase *db = [FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    [db open];
    NSString *sqlStr=[NSString stringWithFormat:@"select INSPECT_ITEM_ID from inspect_process_record where INSPECT_PROCESS_ID='%@' and INSPECT_USER_ITEM_ID !='' and INSPECT_USER_ID='%@'",processId,USERID];
    FMResultSet *resule=[db executeQuery:sqlStr];
    NSMutableArray *arr=[NSMutableArray array];
    while ([resule next]) {
        NSString *ids=[resule stringForColumn:@"INSPECT_ITEM_ID"];
        [arr addObject:ids];
    }
    [db close];
    return arr;
}

//根据父巡检项ID 查询巡检项  （排除已存在巡检项）
+(NSMutableArray *)getItemArrByParentID:(NSString *)parId andProcess:(NSString *)processId{
    FMDatabase *db = [FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    [db open];
    NSMutableArray *array=[self getAllItemIdByProcessMy:processId];
    
    NSString *sqlStr=[NSString stringWithFormat:@"SELECT ID,INSPECT_NAME FROM INSPECT_ITEM WHERE PARENT_ID='%@'",parId];
    
    FMResultSet *resule=[db executeQuery:sqlStr];
    NSMutableArray *arr=[NSMutableArray array];
    while ([resule next]) {
        NSString *ids=[resule stringForColumn:@"ID"];
        NSString *name=[resule stringForColumn:@"INSPECT_NAME"];
        if(![array containsObject:ids]){
            NSDictionary *dic=@{@"id":ids,@"itemName":name};
            [arr addObject:dic];
        }
    }
    
    [db close];
    return arr;
}

//根据巡检流程记录id 查询状态
+(NSString *)getInspectStateByProcessRecordId:(NSString *)prId{
    FMDatabase *db = [FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    [db open];
    NSString *sqlStr=[NSString stringWithFormat:@"SELECT INSPECT_RESULT FROM INSPECT_PROCESS_RECORD WHERE ID='%@'",prId];
    FMResultSet *resule=[db executeQuery:sqlStr];
    NSString *result=@"";
    while ([resule next]) {
        result=[resule stringForColumn:@"INSPECT_RESULT"];
    }
    [db close];
    return result;
}

//根据巡检流程 查询巡检组id（一个流程只有一个巡检组）
+(NSString *)getGroupIdByProcessId:(NSString *)processId{
    FMDatabase *db = [FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    [db open];
    NSString *sqlStr=[NSString stringWithFormat:@"SELECT ID FROM INSPECT_GROUP WHERE INSPECT_PROCESS_ID='%@'",processId];
    FMResultSet *resule=[db executeQuery:sqlStr];
    NSString *ids=@"";
    while ([resule next]) {
        ids=[resule stringForColumn:@"ID"];
    }
    [db close];
    return ids;
    
}

//查询该流程记录是否状态4 待审核
+(BOOL )getProcessRecordState4:(NSString *)processRecordId{
    FMDatabase *db = [FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    [db open];
    NSString *sqlStr=[NSString stringWithFormat:@"select count(1) from inspect_process_record where INSPECT_USER_ITEM_ID=(select INSPECT_USER_ITEM_ID from inspect_process_record where id='%@') and inspect_item_state='4'",processRecordId];
    FMResultSet *resule=[db executeQuery:sqlStr];
    NSString *count;
    while ([resule next]) {
        count=[resule stringForColumn:@"count(1)"];
    }
    [db close];
    if([count isEqualToString:@"0"]){
        return NO;
    }else{
        return YES;
    }
}

//判断该任务下是否已经经过总监处理
+(BOOL )getProcessZongjianState4:(NSString *)processId{
    FMDatabase *db = [FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    [db open];
    NSString *sqlStr=[NSString stringWithFormat:@" select count(1) from INSPECT_PROCESS_RECORD where inspect_item_state='4' and inspect_process_id='%@'",processId];
    FMResultSet *resule=[db executeQuery:sqlStr];
    NSString *count;
    while ([resule next]) {
        count=[resule stringForColumn:@"count(1)"];
    }
    [db close];
    if([count isEqualToString:@"0"]){
        return NO;
    }else{
        return YES;
    }
}

//判断巡检流程记录该条记录是否同步 、同步后不能编辑
+(BOOL )getInspectRecordEditById:(NSString *)totalId{
    FMDatabase *db = [FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    [db open];
    NSString *sqlStr=[NSString stringWithFormat:@" select LOCAL_MODIFY_STATE from INSPECT_PROCESS_RECORD where id='%@' ",totalId];
    FMResultSet *resule=[db executeQuery:sqlStr];
    NSString *localState=@"";
    while ([resule next]) {
        localState=[resule stringForColumn:@"LOCAL_MODIFY_STATE"];
    }
    [db close];
    
    //通过 id 查找到 userItemID
    NSString *userState=[self getUserItemState:totalId];
    return [userState isEqualToString:@""]||[userState isEqualToString:@"1"] || (([userState isEqualToString:@"2"] || [userState isEqualToString:@"5"]) && [localState isEqualToString:@"ADD"]);
}

//查询一键汇总表 同步后不能编辑
+(BOOL )getTotalRecordEditById:(NSString *)totalId{
    FMDatabase *db = [FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    [db open];
    NSString *sqlStr=[NSString stringWithFormat:@" select count(1) from INSPECT_TOTAL_RECORD where id='%@' and LOCAL_MODIFY_STATE in('DOWNLOADED','')",totalId];
    FMResultSet *resule=[db executeQuery:sqlStr];
    NSString *count;
    while ([resule next]) {
        count=[resule stringForColumn:@"count(1)"];
    }
    [db close];
    if([count isEqualToString:@"1"]){
        return YES;
    }else{
        return NO;
    }
}

//判断流程是否结束 5状态
+(NSString *)getInspectStop:(NSString *)processId{
    FMDatabase *db = [FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    [db open];
    NSString *sqlStr=[NSString stringWithFormat:@"select count(DISTINCT(INSPECT_USER_ITEM_ID))as count from INSPECT_PROCESS_RECORD where  INSPECT_USER_ITEM_ID=(select INSPECT_USER_ITEM_ID from inspect_process_record where id='%@') and inspect_item_state in('5') and LOCAL_MODIFY_STATE!='DEL'",processId];
    FMResultSet *resule=[db executeQuery:sqlStr];
    NSString *count;
    while ([resule next]) {
        count=[resule stringForColumn:@"count"];
    }
    [db close];
    //返回0 为整改、返回1、待整改 返回2、整改合格
    return count;
}

//查询该用户巡检项状态
+(NSString * )getUserItemState:(NSString *)recordID{
    FMDatabase *db = [FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    [db open];
    //巡检流程记录
    NSString *sql_1= [NSString stringWithFormat:@"select INSPECT_CURRENT_STATE,ID from INSPECT_USER_ITEM where id=(select INSPECT_USER_ITEM_ID from INSPECT_PROCESS_RECORD where ID='%@')",recordID];
    FMResultSet *result_1=[db executeQuery:sql_1];
    NSString *stateStr=@"";
    while ([result_1 next]) {
        stateStr=[result_1 stringForColumn:@"INSPECT_CURRENT_STATE"];
        if([stateStr isEqualToString:@"3"]){
            NSLog(@"id:%@",[result_1 stringForColumn:@"ID"]);
        }
    }
    [db close];
    return stateStr;
}


//根据巡检项id 查询父级名称
+(NSMutableDictionary *)getParentNameByitemId:(NSString *)itemId{
    FMDatabase *db = [FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    [db open];
    NSString *sqlStr=[NSString stringWithFormat:@"select ID,INSPECT_NAME from INSPECT_ITEM where id = ( select PARENT_ID from INSPECT_ITEM where id= '%@')",itemId];
    FMResultSet *resule=[db executeQuery:sqlStr];
    NSMutableDictionary *dic=[NSMutableDictionary dictionary];
    while ([resule next]) {
        NSString *ids=[resule stringForColumn:@"ID"];
        NSString *name=[resule stringForColumn:@"INSPECT_NAME"];
        [dic setObject:ids forKey:@"id"];
        [dic setObject:name forKey:@"name"];
    }
    [db close];
    return dic;
}

//根据自己id 查询自己名称
+(NSMutableDictionary *)getParentNameByitemIdss:(NSString *)Id{
    FMDatabase *db = [FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    [db open];
    NSString *sqlStr=[NSString stringWithFormat:@"select ID,INSPECT_NAME from INSPECT_ITEM where id ='%@'",Id];
    FMResultSet *resule=[db executeQuery:sqlStr];
    NSMutableDictionary *dic=[NSMutableDictionary dictionary];
    while ([resule next]) {
        NSString *ids=[resule stringForColumn:@"ID"];
        NSString *name=[resule stringForColumn:@"INSPECT_NAME"];
        [dic setObject:ids forKey:@"id"];
        [dic setObject:name forKey:@"name"];
    }
    [db close];
    return dic;
    
    
}


//根据巡检流程记录id 查询详细记录
+(NSMutableDictionary *)queryInspectRecordById:(NSString *)recordId{
    FMDatabase *db = [FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    [db open];
    //巡检流程记录
    NSString *sql_1= [NSString stringWithFormat:@"select * from INSPECT_PROCESS_RECORD where ID='%@'",recordId];
    FMResultSet *result_1 = [db executeQuery:sql_1];
    
    NSMutableDictionary *_gtatsDic;
    while ([result_1 next]) {
        NSDictionary *dic = [result_1 resultDictionary];
        _gtatsDic = [NSMutableDictionary dictionaryWithDictionary:dic];
    }
    [db close];
    return _gtatsDic;
}

//    根据流程id 查询是否已经一键汇总完巡检任务
+(NSArray *)getTotalByProcessID:(NSString *)processId{
    FMDatabase *db=[FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    DBHelper *dbhelp= [DBHelper help];
    NSArray *totalArr=[dbhelp DataBase:db selectKeyTypes:@{@"ID":@"text"} fromTable:INSPECT_TOTAL_RECORD whereCondition:@{@"INSPECT_PROCESS_ID":processId}];
    return totalArr;
}

//  判断一键汇总是否上传
+(BOOL )getTotalByIsSync:(NSString *)processId{
    
    FMDatabase *db = [FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    [db open];
    //巡检流程记录
    NSString *sql_1= [NSString stringWithFormat:@"select * from INSPECT_TOTAL_RECORD where INSPECT_PROCESS_ID='%@' and LOCAL_MODIFY_STATE in('ADD','MOD')",processId];
    FMResultSet *result_1=[db executeQuery:sql_1];
    NSMutableArray *array=[NSMutableArray array];
    while ([result_1 next]) {
        [array addObject:[result_1 stringForColumn:@"ID"]];
    }
    [db close];
    
    if(array.count>0){
        return YES;
    }else{
        return NO;
    }
}

//修改user_item的状态 mod
+(void)updateInspectUserItembyId:(NSString *)ids andState:(int)state{
    FMDatabase *db=[FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    DBHelper *dbhelp= [DBHelper help];
    NSDictionary *dics=@{
                         @"INSPECT_CURRENT_STATE":@(state),
                         @"MODIFY_TIME":[LSUtility nowTime],
                         @"MODIFY_IP":[LSUtility getIPAddress],
                         @"LOCAL_MODIFY_STATE":@"MOD"
                         };
    [dbhelp DataBase:db updateTable:INSPECT_USER_ITEM setKeyValues:dics whereCondition:@{@"ID":ids}];
}

//修改user_item的状态 add
+(void)updateInspectUserItembyIdADD:(NSString *)ids andState:(int)state{
    FMDatabase *db=[FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    DBHelper *dbhelp= [DBHelper help];
    NSDictionary *dics=@{
                         @"INSPECT_CURRENT_STATE":@(state),
                         @"MODIFY_TIME":[LSUtility nowTime],
                         @"MODIFY_IP":[LSUtility getIPAddress],
                         @"LOCAL_MODIFY_STATE":@"ADD"
                         };
    [dbhelp DataBase:db updateTable:INSPECT_USER_ITEM setKeyValues:dics whereCondition:@{@"ID":ids}];
}

//查询是本地新增 还是服务器返回
+(BOOL)updateIsDown:(NSString *)ids table:(NSString *)table{
    FMDatabase *db = [FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    [db open];
    //巡检流程记录
    NSString *sql_1= [NSString stringWithFormat:@"select * from %@ where id='%@' ",table,ids];
    FMResultSet *result_1=[db executeQuery:sql_1];
    NSString *state=@"";
    while ([result_1 next]) {
        state=[result_1 stringForColumn:@"LOCAL_MODIFY_STATE"];
    }
    [db close];
    
    if([state isEqualToString:@"ADD"]){
        return YES;
    }else{
        return NO;
    }
}

//查询user_item的状态
+(NSString *)queryUserItemStateById:(NSString *)ids{
    FMDatabase *db = [FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    [db open];
    //巡检流程记录
    NSString *sql_1= [NSString stringWithFormat:@"select * from INSPECT_USER_ITEM where id='%@'",ids];
    FMResultSet *result_1=[db executeQuery:sql_1];
    NSString *state=@"";
    while ([result_1 next]) {
        state=[result_1 stringForColumn:@"INSPECT_CURRENT_STATE"];
    }
    [db close];
    return state;
}
//查询最近一条状态是否是自己修改

+(BOOL)isLastInspectProcessRecord:(NSString *)userItemId{
    FMDatabase *db = [FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    [db open];
    //巡检流程记录
    //    NSString *sql_1= [NSString stringWithFormat:@"select * from inspect_process_record where INSPECT_USER_ITEM_ID='%@' and inspect_item_state!='4' order by(create_time) desc limit 0,1 ",userItemId];
    NSString *sql_1= [NSString stringWithFormat:@"select * from inspect_process_record where INSPECT_USER_ITEM_ID='%@' order by(create_time) desc limit 0,1 ",userItemId];
    FMResultSet *result_1=[db executeQuery:sql_1];
    NSString *inspectUserId=@"";
    while ([result_1 next]) {
        inspectUserId=DEFISNUL([result_1 stringForColumn:@"CREATE_USER_NAME"]);
    }
    [db close];
    
    if([USERID isEqualToString:inspectUserId]){
        return YES;
    }else{
        return NO;
    }
}

//判断巡检项任务是否完成 。将流程表任务状态都变为5
+(void)processRecordStateExistEnd:(NSString *)processId{
    FMDatabase *db = [FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    [db open];
    //所有的巡检项
    NSString *sqlStr=[NSString stringWithFormat:@"select DISTINCT(INSPECT_USER_ITEM_ID) from INSPECT_PROCESS_RECORD where inspect_process_id ='%@' and (inspect_item_state ='3' or inspect_item_state ='5')",processId];
    FMResultSet *resule=[db executeQuery:sqlStr];
    int i=0;
    while ([resule next]) {
        i++;
    }
    //结束的巡检项  合格的数据 一键汇总后移除
    //    NSString *sqlStr_2=[NSString stringWithFormat:@"select * from INSPECT_PROCESS_RECORD where inspect_process_id ='%@'  and (inspect_item_state in('5') or INSPECT_RESULT='1') GROUP BY INSPECT_USER_ITEM_ID",processId];
    
    NSString *sqlStr_2=[NSString stringWithFormat:@"select * from INSPECT_PROCESS_RECORD where inspect_process_id ='%@'  and inspect_item_state in('5') GROUP BY INSPECT_USER_ITEM_ID",processId];
    FMResultSet *resule_2=[db executeQuery:sqlStr_2];
    int j=0;
    while ([resule_2 next]) {
        j++;
    }
    if(i!=0){
        if(i==j){
            //巡检任务状态变为5
            NSString *sqlStr_3=[NSString stringWithFormat:@"update INSPECT_PROCESS  set INSPECT_STATE='5',LOCAL_MODIFY_STATE='MOD',MODIFY_TIME='%@' where ID='%@'",[LSUtility nowTime],processId];
            if([db executeUpdate:sqlStr_3]){
                NSLog(@"该任务已结束");
            }
        }else{
            //巡检任务状态变为3
            //        NSString *sqlStr_4=[NSString stringWithFormat:@"update INSPECT_PROCESS  set INSPECT_STATE='3',LOCAL_MODIFY_STATE='MOD',LOCAL_MODIFY_TIME='%@' where ID='%@'",[LSUtility nowTime],processId];
            //        if([db executeUpdate:sqlStr_4]){
            //            NSLog(@"该任务未结束");
            //        }
            NSLog(@"该任务未结束");
        }
    }
    [db close];
}

//修改巡检流程的状态
+(void)updateInspectProcessbyId:(NSString *)ids andState:(int)state{
    FMDatabase *db=[FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    DBHelper *dbhelp= [DBHelper help];
    NSDictionary *dics=@{
                         @"INSPECT_CURRENT_STATE":@(state),
                         @"MODIFY_TIME":[LSUtility nowTime],
                         @"MODIFY_IP":[LSUtility getIPAddress],
                         @"LOCAL_MODIFY_STATE":@"MOD"
                         };
    [dbhelp DataBase:db updateTable:INSPECT_PROCESS setKeyValues:dics whereCondition:@{@"ID":ids}];
}

//查询有无督办单 并且返回督办单id
+(NSString *)queryInspectSuperProcessId:(NSString *)userItemId{
    FMDatabase *db = [FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    [db open];
    //巡检流程记录
    NSString *sql_1= [NSString stringWithFormat:@"select * from INSPECT_USER_ITEM where id='%@'",userItemId];
    FMResultSet *result_1=[db executeQuery:sql_1];
    NSString *superProcessId=@"";
    while ([result_1 next]) {
        superProcessId=DEFISNUL([result_1 stringForColumn:@"SUPER_PROCESS_ID"]);
    }
    [db close];
    return superProcessId;
}
//判断是否是该巡检组组长
+(BOOL)queryInspcetGroupLeader:(NSString *)gruopId{
    FMDatabase *db = [FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    [db open];
    //巡检流程记录
    NSString *sql_1= [NSString stringWithFormat:@"select * from INSPECT_GROUP_USER where INSPECT_GROUP_id='%@' and inspect_user_type='1'",gruopId];
    FMResultSet *result_1=[db executeQuery:sql_1];
    NSString *inspectUserId=@"";
    while ([result_1 next]) {
        inspectUserId=DEFISNUL([result_1 stringForColumn:@"INSPECT_USER_ID"]);
    }
    [db close];
    
    if([inspectUserId isEqualToString:USERID]){
        return YES;
    }else{
        return NO;
    }
}

+(NSString *)quertInspectStateByProcessId:(NSString *)processId{
    FMDatabase *db = [FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    [db open];
    //巡检流程记录
    NSString *sql_1= [NSString stringWithFormat:@"select * from INSPECT_PROCESS  where id='%@'",processId];
    FMResultSet *result_1=[db executeQuery:sql_1];
    NSString *state=@"";
    while ([result_1 next]) {
        state=DEFISNUL([result_1 stringForColumn:@"INSPECT_STATE"]);
    }
    [db close];
    return state;
}


//得到任务名字和创建时间
+(NSDictionary *)quertInspectProcessName:(NSString *)processId{
    FMDatabase *db = [FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    [db open];
    //巡检流程记录
    NSString *sql_1= [NSString stringWithFormat:@"select * from INSPECT_PROCESS  where id='%@'",processId];
    FMResultSet *result_1=[db executeQuery:sql_1];
    NSMutableDictionary *dic=[NSMutableDictionary dictionary];
    while ([result_1 next]) {
        NSString *name=DEFISNUL([result_1 stringForColumn:@"INSPECT_NAME"]);
        [dic setObject:name forKey:@"title"];
        NSString *time=[result_1 stringForColumn:@"CREATE_TIME"];
        NSString *subTitle= [time substringToIndex:10];
        [dic setObject:subTitle forKey:@"time"];
    }
    [db close];
    return dic;
}

// 颜色转图片
+ (UIImage *)createImageWithColor:(UIColor *)color {
    CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return theImage;
}

// 比较两个日期时间大小
+ (int)compareLocalDate:(NSString*)date01 withServerDate:(NSString*)date02 {
    int ci;
    NSDateFormatter *df = [[NSDateFormatter alloc] init];
    [df setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSDate *dt1 = [[NSDate alloc] init];
    NSDate *dt2 = [[NSDate alloc] init];
    dt1 = [df dateFromString:date01];
    dt2 = [df dateFromString:date02];
    NSComparisonResult result = [dt1 compare:dt2];
    switch (result)
    {
            //date02比date01大
        case NSOrderedAscending: ci=1; break;
            //date02比date01小
        case NSOrderedDescending: ci=-1; break;
            //date02=date01
        case NSOrderedSame: ci=0; break;
        default: NSLog(@"erorr dates %@, %@", dt2, dt1); break;
    }
    return ci;
}

// 返回随机颜色
+ (UIColor *)randomColor {
    UIColor *color = [UIColor colorWithRed:arc4random_uniform(255)/255.0 green:arc4random_uniform(255)/255.0 blue:arc4random_uniform(255)/255.0 alpha:1];
    return color;
}

// 过滤掉字符串前面的n个0
+ (NSString*)getTheCorrectNum:(NSString*)tempString
{
    while ([tempString hasPrefix:@"0"])
    {
        tempString = [tempString substringFromIndex:1];
        NSLog(@"压缩之后的tempString:%@",tempString);
    }
    return tempString;
}

// 查找当前巡检项当前状态的条数
+ (int)getInspectItemCountByUserItemID:(NSString *)userItemID withState:(NSString *)state {
    FMDatabase *db = [FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    [db open];
    NSString *sql = [NSString stringWithFormat:@"SELECT count( DISTINCT(CREATE_TIME)) as count FROM INSPECT_PROCESS_RECORD WHERE INSPECT_USER_ITEM_ID = '%@' AND INSPECT_ITEM_STATE = '%@'", userItemID, state];
    FMResultSet *result = [db executeQuery:sql];
    
    int count = 0;
    while ([result next]) {
        count = [result intForColumn:@"count"];
    }
    [db close];
    return count;
}

//根据用户巡检项id 和状态返回巡检记录id
+(NSString *)quertinspectRecordStateByUserItemId:(NSString *)userItemId AndState:(NSString *)state{
    FMDatabase *db = [FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    [db open];
    NSString *sql = [NSString stringWithFormat:@"SELECT * FROM INSPECT_PROCESS_RECORD WHERE INSPECT_USER_ITEM_ID = '%@'  ORDER BY (CREATE_time) DESC limit 0,1", userItemId];
    FMResultSet *result = [db executeQuery:sql];
    NSString *recordId=@"";
    while ([result next]) {
        recordId = [result stringForColumn:@"id"];
    }
    [db close];
    
    return recordId;
}

// 根据二维码生成图片
+ (UIImage *)QrCodeIsGenerated:(NSString *)dataString {
    // 1.创建过滤器
    CIFilter *filter = [CIFilter filterWithName:@"CIQRCodeGenerator"];
    
    // 2.恢复默认
    [filter setDefaults];
    
    // 3.给过滤器添加数据(正则表达式/账号和密码)
    NSData *data = [dataString dataUsingEncoding:NSUTF8StringEncoding];
    [filter setValue:data forKeyPath:@"inputMessage"];
    
    // 4.获取输出的二维码
    CIImage *outputImage = [filter outputImage];
    
    // 生成高清二维码图
    CGRect extent = CGRectIntegral(outputImage.extent);
    CGFloat scale = MIN(200 / CGRectGetWidth(extent), 200 / CGRectGetHeight(extent));
    
    // 1.创建bitmap;
    size_t width = CGRectGetWidth(extent) * scale;
    size_t height = CGRectGetHeight(extent) * scale;
    CGColorSpaceRef cs = CGColorSpaceCreateDeviceGray();
    CGContextRef bitmapRef = CGBitmapContextCreate(nil, width, height, 8, 0, cs, (CGBitmapInfo)kCGImageAlphaNone);
    CIContext *context = [CIContext contextWithOptions:nil];
    CGImageRef bitmapImage = [context createCGImage:outputImage fromRect:extent];
    CGContextSetInterpolationQuality(bitmapRef, kCGInterpolationNone);
    CGContextScaleCTM(bitmapRef, scale, scale);
    CGContextDrawImage(bitmapRef, extent, bitmapImage);
    
    // 2.保存bitmap到图片
    CGImageRef scaledImage = CGBitmapContextCreateImage(bitmapRef);
    CGContextRelease(bitmapRef);
    CGImageRelease(bitmapImage);
    return [UIImage imageWithCGImage:scaledImage];
}

// NSString单引号变双引号
+ (NSString *)stringWithString:(NSString *)jsonString {
    if (jsonString == nil) {
        return nil;
    }
    
    NSMutableString *mutStr = [NSMutableString
                               stringWithString:jsonString];
    NSRange range = {0,mutStr.length};
    
    //单引号变双引号
    [mutStr replaceOccurrencesOfString:@"\'"
                            withString:@"\""
                               options:NSLiteralSearch range:range];
    return mutStr;
}

// 获取分值上线
+ (NSString *)getInspectScore:(NSString *)inspectItemID {
    FMDatabase *db = [FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    [db open];
    NSString *sql = [NSString stringWithFormat:@"SELECT INSPECT_SCORE FROM INSPECT_ITEM WHERE ID = '%@'", inspectItemID];
    FMResultSet *result = [db executeQuery:sql];
    
    NSString *scoreLimit;
    while ([result next]) {
        scoreLimit = [result stringForColumn:@"INSPECT_SCORE"];
    }
    [db close];
    return scoreLimit;
}

//是否打水印
+(BOOL)isWaterMark{
    NSDictionary *dic=  [LSUtility querySystemConfig:@"PHOTO_WATERMARK_SWITH"];
    if(dic){
        NSString *str=dic[@"CONFVALUE"];
        if([str isEqualToString:@"on"]||[str isEqualToString:@"ON"]){
            return YES;
        }else{
            return NO;
        }
    }else{
        //查询不到配置 没有水印
        return NO;
    }
}

//水印打印内容
+(NSArray *)queryPhotoWaterarkWord{
    NSDictionary *dic=  [LSUtility querySystemConfig:@"PHOTO_WATERMARK_WORD"];
    NSArray* array;
    if(dic){
        NSString *str=dic[@"CONFVALUE"];
        //根据逗号分隔
        array=[str componentsSeparatedByString:@","];
        return array;
    }else{
        //查询不到配置 没有水印
        return nil;
    }
}
//是否推送
+(BOOL)isPushMark{
    NSDictionary *dic=  [LSUtility querySystemConfig:@"SIGN_SWITCH"];
    if(dic){
        NSString *str=dic[@"CONFVALUE"];
        if([str isEqualToString:@"on"]||[str isEqualToString:@"ON"]){
            return YES;
        }else{
            return NO;
        }
    }else{
        return NO;
    }
}
//查询推送时间
+(NSMutableDictionary *)queryPushTimeDic{
    NSDictionary *dic=  [LSUtility querySystemConfig:@"SIGN_TIME"];
    if(dic){
        NSString *str=dic[@"CONFVALUE"];
        NSArray *times = [str componentsSeparatedByString:@","];
        NSMutableDictionary *dicTime = [NSMutableDictionary dictionary];
        for (NSString *time in times) {
            if ([time containsString:@"-"]) {
                NSArray *times = [time componentsSeparatedByString:@"-"];
                if(times.count>1){
                    [dicTime setValue:times[0] forKey:times[1]];
                }
            }
        }
        return dicTime;
    }else{
        return nil;
    }
}
//查询推送内容
+(NSMutableDictionary *)queryPushStringDic{
    NSDictionary *dic=  [LSUtility querySystemConfig:@"SIGN_NOTE"];
    if(dic){
        NSString *str=dic[@"CONFVALUE"];
        NSArray *notices = [str componentsSeparatedByString:@";"];
        NSMutableDictionary *dicNotice = [NSMutableDictionary dictionary];
        for (NSString *notice in notices) {
            if ([notice containsString:@"-"]) {
                NSArray *notices = [notice componentsSeparatedByString:@"-"];
                if (notices.count>1) {
                    [dicNotice setValue:notices[1] forKey:notices[0]];
                }
            }
        }
        return dicNotice;
    }else{
        return nil;
    }
}
+(void)pushNotification{
    BOOL push= [LSUtility isPushMark];
    if (push) {
        [[UIApplication sharedApplication] cancelAllLocalNotifications];
        NSDictionary *dicTime = [LSUtility queryPushTimeDic];
        NSDictionary *dicStr = [LSUtility queryPushStringDic];
        NSArray *times = [dicTime allKeys];
        
        for (NSString *time in times) {
            NSString *value = [dicTime valueForKey:time];
            NSString *str = dicStr[value];
            if (str&&str.length>0) {
                
            }else{
                if ([value intValue]==0) {
                    str = @"您还未签到，请尽快签到！";
                }else if([value intValue] == 1){
                    str = @"您还未签退，请尽快签退！";
                }else{
                    str = @"";
                }
            }
    

            [LSUtility pushTuisongTime:time str:str name:@"name"];
        }
    }
}


+(void)pushTuisongTime:(NSString *)time str:(NSString *)str name:(NSString *)name{
    // 设置一个按照固定时间的本地推送
    //    NSDate *now = [NSDate date];
    //    //取得系统时间
    //    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    //    NSDateComponents *components = [[NSDateComponents alloc] init];
    //    NSInteger unitFlags = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitWeekday | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
    //    components = [calendar components:unitFlags fromDate:now];
    //    NSInteger hour = [components hour];
    //    NSInteger min = [components minute];
    //    NSInteger sec = [components second];
    //    NSInteger week = [components weekday];
    //    NSLog(@"现在是%ld：%ld：%ld,周%ld",hour,min,sec,week);
    
    UILocalNotification *localNotification = [[UILocalNotification alloc] init];
    //设置时区（跟随手机的时区）
    localNotification.timeZone = [NSTimeZone defaultTimeZone];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"HH:mm"];
    localNotification.fireDate = [NSDate dateWithTimeIntervalSinceNow:3];
    localNotification.fireDate = [formatter dateFromString:time];
    localNotification.alertBody = str;
    localNotification.applicationIconBadgeNumber = 1;
    localNotification.soundName = UILocalNotificationDefaultSoundName;
    //循环通知的周期
    localNotification.repeatInterval = kCFCalendarUnitDay;
    //设置userinfo方便撤销
    localNotification.userInfo = @{name:str};
    //启动任务
    [[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
}
//按名字取消通知
-(void)cancelLocalNotification:(NSString *)name{
    for (UILocalNotification *obj in [UIApplication sharedApplication].scheduledLocalNotifications) {
        if ([obj.userInfo.allKeys containsObject:name]) {
            [[UIApplication sharedApplication] cancelLocalNotification:obj];
        }
    }

}
//直接取消全部本地通知
-(void)cancelAllLocalNotifications{
    [[UIApplication sharedApplication] cancelAllLocalNotifications];
}

/**
 *  旁站 当前是否超过结束时间 是否被开始时间或者结束时间日记带入
 *  满足其一返回NO 不可编辑
 *  其余情况可编辑 返回yes
 */
+ (BOOL)siteEditForendTimeAndSiteRecordId:(NSString*)siteId beginTine:(NSString *)beginTime endTime:(NSString*)endTime
{
//    NSString *time=[timeStr substringToIndex:10];
    //当天日期
//    NSString *nowStr=[[LSUtility TimeNow] substringToIndex:10];
    //开始日期
    NSString *beginStr = [beginTime substringToIndex:10];
    //结束日期
    NSString *endStr = [endTime substringToIndex:10];

    FMDatabase *db=[FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    [db open];
    //查询开始日期和结束日期两天 日记中引入旁站
    NSString *sql=[NSString stringWithFormat:@"SELECT * FROM WORK_DIARY where PRO_ID='%@' and DIARY_USER='%@' AND (CREATE_TIME LIKE '%@%%' or CREATE_TIME LIKE '%@%%') and SITE_INFO like '%%\"recordId\"%%\"%@\"%%\'",PROID,USERID,beginStr,endStr,siteId];
    FMResultSet *result=[db executeQuery:sql];
    NSMutableArray *arr=[NSMutableArray array];
    while ([result next]) {
        //存放记录id的字段
        NSString *tourInfo=[result stringForColumn:@"id"];
        [arr addObject:tourInfo];
    }
    //旁站被引入
    if(arr.count>0){
        return NO;
    }
    //旁站未被引入
    else{
       //判断当前时间是否超过 结束时间24：00
       long time= [self timeDifferenceDay:endStr];
        if(time<0){
            return NO;
        }else{
            return YES;
        }
    }
}


// 位置回显数组
+ (NSMutableArray *)createDataSource:(NSString *)patentID {
    // 获取项目ID
    NSString *proID = DEF_PERSISTENT_GET_OBJECT(@"proid");
    
    NSString *Sql = [NSString stringWithFormat:@"SELECT * FROM ADDRESS WHERE id = '%@' AND PRO_ID = '%@' ORDER BY ADDRESS_NAME", patentID, proID];
    FMDatabase *db=[FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    [db open];
    // 获取查询的结果集
    FMResultSet *result = [db executeQuery:Sql];
    NSMutableArray *moedlArr = [NSMutableArray array];
    while ([result next]) {
        AddressModel *aModel = [[AddressModel alloc] init];
        
        aModel.ID = [result stringForColumn:@"ID"];
        aModel.PRO_ID = [result stringForColumn:@"PRO_ID"];
        aModel.PATENT_ID = [result stringForColumn:@"PATENT_ID"];
        aModel.ADDRESS_NAME = [result stringForColumn:@"ADDRESS_NAME"];
        aModel.ADDRESS_TYPE = [result stringForColumn:@"ADDRESS_TYPE"];
        aModel.A__LONG = [result doubleForColumn:@"A__LONG"];
        aModel.A__LAT = [result doubleForColumn:@"A__LAT"];
        aModel.A__HEIGHT = [result doubleForColumn:@"A__HEIGHT"];
        aModel.B__LONG = [result doubleForColumn:@"B__LONG"];
        aModel.B__LAT = [result doubleForColumn:@"B__LAT"];
        aModel.B__HEIGHT = [result doubleForColumn:@"B__HEIGHT"];
        aModel.C__LONG = [result doubleForColumn:@"C__LONG"];
        aModel.C__LAT = [result doubleForColumn:@"C__LAT"];
        aModel.C__HEIGHT = [result doubleForColumn:@"C__HEIGHT"];
        aModel.D__LONG = [result doubleForColumn:@"D__LONG"];
        aModel.D__LAT = [result doubleForColumn:@"D__LAT"];
        aModel.D__HEIGHT = [result doubleForColumn:@"D__HEIGHT"];
        aModel.STATE = [result intForColumn:@"STATE"];
        aModel.SCALE = [result stringForColumn:@"SCALE"];
        aModel.IMAGE_INFO = [result stringForColumn:@"IMAGE_INFO"];
        aModel.IMAGE_INFO_DESC = [result stringForColumn:@"IMAGE_INFO_DESC"];
        aModel.EXTEND_INFO = [result stringForColumn:@"EXTEND_INFO"];
        aModel.CREATE_USER_NAME = [result stringForColumn:@"CREATE_USER_NAME"];
        aModel.CREATE_TIME = [result stringForColumn:@"CREATE_TIME"];
        aModel.CREATE_IP = [result stringForColumn:@"CREATE_IP"];
        aModel.MODIFY_USER_NAME = [result stringForColumn:@"MODIFY_USER_NAME"];
        aModel.MODIFY_IP = [result stringForColumn:@"MODIFY_IP"];
        aModel.MODIFY_TIME = [result stringForColumn:@"MODIFY_TIME"];
        
        NSMutableDictionary *dic = [[NSMutableDictionary alloc] initWithObjectsAndKeys:aModel.ADDRESS_NAME,@"addressName", aModel.IMAGE_INFO,@"imageName", aModel.ID,@"ID", aModel, @"aModel", nil];
        [moedlArr addObject:dic];
    }
    [db close];
    return moedlArr;
}

// 弹出WDDAlertController
+ (void)pushWDDAlertVC:(WDDAlertController *)alertVC withTitle:(NSString *)titleStr andMessageStr:(NSString *)messageStr  {
    
    // 修改标题的内容，字号，颜色。使用的key值是“attributedTitle”
    NSMutableAttributedString *titleMAttStr = [[NSMutableAttributedString alloc] initWithString:titleStr];
    [titleMAttStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:15] range:NSMakeRange(0, [[titleMAttStr string] length])];
    [titleMAttStr addAttribute:NSForegroundColorAttributeName value:UIColorFromRGB(0x009688) range:NSMakeRange(0, [[titleMAttStr string] length])];
    [alertVC setValue:titleMAttStr forKey:@"attributedTitle"];
    
    // 修改提示信息
    NSMutableAttributedString *alertControllerMessageStr = [[NSMutableAttributedString alloc] initWithString:messageStr];
    [alertControllerMessageStr addAttribute:NSForegroundColorAttributeName value:mainTitleColor range:NSMakeRange(0, [alertControllerMessageStr length])];
    [alertControllerMessageStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:13] range:NSMakeRange(0, [alertControllerMessageStr length])];
    [alertVC setValue:alertControllerMessageStr forKey:@"attributedMessage"];
}
//查找监理单位
+(NSMutableDictionary *)getjianliDanwei{
    // 查找监理单位
    NSString *sqlStr = [NSString stringWithFormat:@"SELECT ID, PRO_UNIT_NAME FROM PROJECT_UNIT WHERE PRO_ID = '%@' AND PRO_UNIT_TYPE = 'UNIT_00'", DEF_PERSISTENT_GET_OBJECT(@"proid")];
    FMDatabase *db = [FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    [db open];
    FMResultSet *result = [db executeQuery:sqlStr];
    NSMutableDictionary *jianliDanwei = [NSMutableDictionary dictionary];
    while ([result next]) {
        // 单位名称
        NSString *proName = [result stringForColumn:@"PRO_UNIT_NAME"];
        [jianliDanwei setValue:proName forKey:@"name"];
        NSString *supervisorProUnitId = [result stringForColumn:@"ID"];
        [jianliDanwei setValue:supervisorProUnitId forKey:@"id"];
    }
    [db close];
    return jianliDanwei;
}
//获取天气地区
+(NSMutableArray *)getWeatherArea{
    NSMutableArray *array = [NSMutableArray array];
    NSMutableArray *wArr = DEF_PERSISTENT_GET_OBJECT(@"WEATHER");
    if(wArr.count>0){
        for (NSDictionary *wdic in wArr) {
            for (NSString *city in wdic) {
                [array addObject:city];
            }
        }
    }
    return array;
}

+(CGFloat)cellHeightWithObj:(NSString *)string Limitheight:(CGFloat)height subtractWidth:(CGFloat)width {
    CGFloat cellHeight = height;
    CGFloat mWidth = [UIScreen mainScreen].bounds.size.width - width;
    cellHeight = [string boundingRectWithSize:CGSizeMake(mWidth,MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin  attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:17*BIZ]} context:nil].size.height;
    if(cellHeight<=height){
        return height;
    }else{
        return cellHeight;
    }
}

//根据项目角色查询人员 姓名和ID
+(NSMutableArray *)queryByType:(NSString *)type{
    FMDatabase *db=[FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    [db open];
    NSString *sql=[NSString stringWithFormat:@"SELECT USER_ID FROM PROJECT_USER WHERE PRO_ID='%@' AND USER_TYPE='%@'",PROID,type];
    FMResultSet *result=[db executeQuery:sql];
    NSMutableArray *arrName=[NSMutableArray array];
    NSMutableArray *strArr = [NSMutableArray array];
    while ([result next]) {
        NSString *userid=[result stringForColumn:@"USER_ID"];
        if (![strArr containsObject:userid]) {
            NSString *name=[LSUtility getuserIdByUserName:userid][@"REAL_NAME"];
            NSMutableDictionary *dic = [NSMutableDictionary dictionary];
            [dic setValue:DEFISNUL(userid) forKey:@"userid"];
            [dic setValue:DEFISNUL(name) forKey:@"username"];
            [strArr addObject:userid];
            [arrName addObject:dic];
        }
    }
    return arrName;
}
@end

